Unit 3 subjective questions UIKit Controls
INT372 — Iphone Application Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define UIButton and explain how the target-action mechanism is used to handle a button tap in an iOS application.
Model answer
UIButton is a UIKit control that allows the user to initiate an action by tapping it. A button can display a title, image, or both and can have different appearances for states such as normal, highlighted, selected, and disabled.
Target-action mechanism:
- The target is the object that receives the event, usually a view controller.
- The action is the method executed when the event occurs.
- The control event specifies when the action should be invoked, such as
.touchUpInside.
Example:
Swiftlet submitButton = UIButton(type: .system) submitButton.setTitle("Submit", for: .normal) submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside) @objc func submitTapped() { print("Submit button tapped") }Buttons can also be connected through Interface Builder by creating an
IBAction. The button should have suitable constraints, readable text, and an accessibility label. -
Question 2 of 20
Explain the purpose of UITextView and describe how the keyboard can be dismissed after multiline text entry.
Model answer
UITextView is a scrollable and editable control used to display or accept multiline text. It is suitable for comments, descriptions, notes, and messages.
Important properties:
text: Gets or sets the displayed text.font: Sets the text font.textColor: Sets the text color.isEditable: Determines whether the user can edit the content.isScrollEnabled: Enables scrolling for long content.delegate: Receives editing-related events.
Unlike
UITextField, a text view normally inserts a new line when Return is pressed. The keyboard can be dismissed using a toolbar button or another user action.Example:
Swift@IBAction func doneTapped(_ sender: UIBarButtonItem) { view.endEditing(true) }Alternatively, a tap gesture can be added to the parent view:
Swiftlet tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tap) @objc func dismissKeyboard() { view.endEditing(true) }The controller can also adopt
UITextViewDelegateto validate input or respond when editing begins and ends. -
Question 3 of 20
Describe UITextField and explain how its input behavior and appearance can be customized.
Model answer
UITextField is a UIKit control designed for single-line text input. It is commonly used for names, email addresses, passwords, phone numbers, and search values.
Input customization:
keyboardType: Selects keyboards such as.emailAddress,.numberPad, or.phonePad.isSecureTextEntry: Hides password characters.autocapitalizationType: Controls automatic capitalization.autocorrectionType: Enables or disables autocorrection.returnKeyType: Changes the Return key to Done, Next, Search, and so on.inputView: Replaces the standard keyboard with a custom input control.inputAccessoryView: Adds a toolbar above the keyboard.
Appearance customization:
- Set
borderStyle,font,textColor,backgroundColor, andplaceholder. - Use
leftViewandrightViewto display icons. - Customize
layer.cornerRadiusandlayer.borderWidth.
Example:
SwiftemailField.placeholder = "Enter email" emailField.keyboardType = .emailAddress emailField.autocapitalizationType = .none emailField.autocorrectionType = .no emailField.borderStyle = .roundedRect passwordField.isSecureTextEntry = true passwordField.returnKeyType = .doneA
UITextFieldDelegatecan validate characters, move between fields, and dismiss the keyboard. -
Question 4 of 20
Distinguish between UITextField and UITextView with suitable use cases.
Model answer
UITextFieldandUITextViewboth accept text, but they are intended for different forms of input.Feature UITextField UITextView Input type Single-line input Multiline input Typical use Username, email, password Comments, notes, descriptions Return key Often submits or moves to the next field Normally inserts a new line Scrolling Limited to horizontal text behavior Supports vertical scrolling Placeholder Built-in placeholderpropertyUsually implemented manually Delegate UITextFieldDelegateUITextViewDelegateBase class UIControlUIScrollViewUse
UITextFieldwhen:- The value is short and structured.
- A specific keyboard type is required.
- The Return key should submit or navigate between inputs.
Use
UITextViewwhen:- The user needs to enter multiple lines.
- The content may be lengthy and scrollable.
- Rich or attributed text must be displayed or edited.
Both controls should validate input and handle keyboard appearance appropriately.
-
Question 5 of 20
What is UISwitch? Explain how to configure it and respond to changes in its state.
Model answer
UISwitch is a two-state UIKit control representing an on/off or true/false setting. It is suitable for options such as enabling notifications, dark mode, sound, or location services.
Important properties and methods:
isOn: Returns or changes the current Boolean state.setOn(_:animated:): Changes the state with optional animation.onTintColor: Sets the color shown in the on state.thumbTintColor: Changes the thumb color..valueChanged: Event generated when the user changes the switch.
Example:
Swiftlet notificationSwitch = UISwitch() notificationSwitch.isOn = true notificationSwitch.addTarget(self, action: #selector(switchChanged), for: .valueChanged) @objc func switchChanged(_ sender: UISwitch) { if sender.isOn { print("Notifications enabled") } else { print("Notifications disabled") } }The setting can be saved in
UserDefaultsand restored when the application starts. A descriptive label should be placed beside the switch so the meaning of each state is clear. -
-
Question 6 of 20
Explain the role of UIImageView and discuss the different content modes used to display an image.
Model answer
UIImageView is a UIKit view used to display a single image or a sequence of animated images. Images can come from the asset catalog, application bundle, system symbols, or a remote source.
Example:
Swiftlet imageView = UIImageView() imageView.image = UIImage(named: "profile") imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = trueCommon content modes:
.scaleToFill: Scales the image to fill the bounds and may distort it..scaleAspectFit: Preserves the aspect ratio and displays the complete image; empty space may remain..scaleAspectFill: Preserves the aspect ratio and fills the entire view; some parts may be cropped..center: Displays the image at its original size in the center.
Additional points:
- Set
clipsToBoundstotruewhen cropped content must not extend beyond the view. - Use
tintColorwith template images or SF Symbols. UIImageViewdoes not accept touches by default; setisUserInteractionEnabled = trueif gesture handling is needed.- Large images should be resized or loaded efficiently to reduce memory usage.
-
Question 7 of 20
Design a small user profile application using UIButton, UITextField, UITextView, UISwitch, and UIImageView. Explain the implementation and validation process.
Model answer
A user profile application can collect a name, email address, biography, profile image, and notification preference.
Suggested controls:
UIImageViewto display the profile photograph.UITextFieldcontrols for name and email.UITextViewfor a multiline biography.UISwitchfor notification preference.UIButtonto choose an image and save the profile.
Implementation steps:
- Create the interface using Interface Builder or programmatic views.
- Add Auto Layout constraints so the screen adapts to different devices.
- Set the email field's keyboard type to
.emailAddress. - Use
UIImagePickerControllerorPHPickerViewControllerto select a profile image. - Dismiss the keyboard with
view.endEditing(true). - Validate all required inputs when Save is tapped.
- Display an alert if validation fails.
- Store or pass the valid profile information.
Save logic example:
Swift@IBAction func saveProfile(_ sender: UIButton) { view.endEditing(true) guard let name = nameField.text, !name.isEmpty, let email = emailField.text, email.contains("@") else { showMessage("Enter a valid name and email address") return } let bio = bioTextView.text ?? "" let notificationsEnabled = notificationSwitch.isOn print(name, email, bio, notificationsEnabled) }The application should also provide accessibility labels, clear error messages, safe keyboard handling, and appropriate content modes for the image.
-
Question 8 of 20
Explain the concept of views in UIKit, including view hierarchy, frames, bounds, and Auto Layout.
Model answer
A view is an instance of
UIViewor one of its subclasses. It occupies a rectangular area, draws content, and may respond to user interaction. Controls such as buttons, labels, text fields, and image views are specialized views.View hierarchy:
- Views are arranged in a parent-child structure.
- A parent is called a
superview. - Child views are stored in the
subviewsarray. addSubview(_:)adds a child view.- The order of subviews affects which view appears in front.
Frame and bounds:
framedescribes a view's size and position in its superview's coordinate system.boundsdescribes the view's internal coordinate system and normally begins at(0, 0).centerspecifies the center point in the superview's coordinate system.
Auto Layout:
- Auto Layout positions and sizes views using constraints.
- Constraints express relationships such as leading, trailing, top, bottom, width, and height.
- Safe-area constraints prevent content from overlapping system areas.
- Intrinsic content size helps size controls based on their content.
A well-designed hierarchy groups related controls, avoids unnecessary nesting, and uses constraints that adapt to screen size and orientation.
-
Question 9 of 20
Describe the architecture and implementation of a multi-view iOS application. What role does each view controller play?
Model answer
A multi-view application contains more than one screen, with each screen generally managed by a separate
UIViewController. Examples include applications with login, list, detail, settings, and profile screens.Role of a view controller:
- Creates or loads its view hierarchy.
- Handles control events and user interaction.
- Manages screen-specific data.
- Coordinates navigation to another controller.
- Responds to lifecycle methods such as
viewDidLoad,viewWillAppear, andviewDidDisappear.
Implementation approaches:
- Create multiple view controllers in a storyboard or as Swift classes.
- Design the user interface for each controller.
- Embed the initial controller in a navigation controller when hierarchical navigation is needed.
- Connect screens with segues or perform programmatic navigation.
- Pass required data before the destination appears.
- Use delegation, closures, notifications, or shared models to return data.
Important design principles:
- Each controller should have a clear and limited responsibility.
- Data should be stored in models rather than duplicated across screens.
- Navigation should be predictable and support the standard Back operation.
- Controllers should release resources and avoid strong reference cycles.
This structure improves modularity, maintainability, and reuse.
-
Question 10 of 20
Define a segue and explain how it is created, triggered, and prepared in a storyboard-based iOS application.
Model answer
A segue represents a transition from one view controller to another in a storyboard. It stores information about the source, destination, transition style, and optional identifier.
Creating a segue:
- Control-drag from a button or view controller to the destination controller.
- Select a segue type such as Show, Present Modally, or Custom.
- Assign an identifier in the Attributes inspector.
A manual segue can be triggered with:
SwiftperformSegue(withIdentifier: "showDetails", sender: selectedItem)Before the transition, UIKit calls
prepare(for:sender:). This method is used to configure the destination and pass data.Swiftoverride func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetails", let destination = segue.destination as? DetailViewController, let item = sender as? Item { destination.item = item } }If the destination is embedded in another controller, such as a navigation controller, the required child controller must first be obtained.
shouldPerformSegue(withIdentifier:sender:)may be used to prevent a transition when validation fails. -
Question 11 of 20
Explain how another view controller can be called using a UINavigationController. Distinguish between pushing and presenting a controller.
Model answer
UINavigationControllermanages a stack of view controllers and provides hierarchical navigation with a navigation bar and Back button.Pushing a controller:
Swiftlet details = DetailViewController() navigationController?.pushViewController(details, animated: true)If the controller is stored in a storyboard:
Swiftlet storyboard = UIStoryboard(name: "Main", bundle: nil) let details = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController navigationController?.pushViewController(details, animated: true)The top controller can be removed using:
SwiftnavigationController?.popViewController(animated: true)Push versus modal presentation:
- Push adds a controller to a navigation stack and is suitable for parent-to-detail movement.
- Present displays a controller modally and is suitable for tasks such as creating an item, signing in, or choosing settings.
- A pushed controller normally displays a Back button automatically.
- A presented controller usually needs its own Done or Cancel action and is dismissed using
dismiss(animated:).
The navigation controller itself should usually be established before attempting to push another controller.
-
Question 12 of 20
Explain different techniques for passing and receiving data between view controllers, including forward and backward data transfer.
Model answer
Data transfer between view controllers should use a method appropriate to the navigation direction and relationship between screens.
Forward data transfer:
- Set public properties on the destination controller.
- Pass data in
prepare(for:sender:)before a segue. - Use dependency injection through an initializer for programmatic controllers.
Swiftoverride func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? DetailViewController { destination.product = selectedProduct } }Backward data transfer:
- Delegate pattern: The destination defines a protocol, and the source adopts it.
- Closure: The destination invokes a closure before it is removed.
- Unwind segue: Returns to an earlier storyboard controller.
- NotificationCenter: Broadcasts data to loosely coupled listeners, though it should not be overused.
- Shared model: Both controllers access a common model or store.
Closure example:
Swifteditor.onSave = { [weak self] updatedName in self?.nameLabel.text = updatedName }Best practices:
- Pass model objects rather than unrelated individual values.
- Avoid global variables for screen-to-screen transfer.
- Use
[weak self]where closures may create reference cycles. - Update visible controls on the main thread.
- Keep data ownership and responsibilities clear.
-
Question 13 of 20
What is UISegmentedControl? Explain how it can be used to switch between related options or views.
Model answer
UISegmentedControl displays a horizontal group of mutually exclusive segments. It is suitable when the user must select exactly one option from a small set, such as List/Grid, Day/Week/Month, or Login/Register.
Configuration example:
Swiftlet control = UISegmentedControl(items: ["List", "Grid"]) control.selectedSegmentIndex = 0 control.addTarget(self, action: #selector(segmentChanged), for: .valueChanged) @objc func segmentChanged(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { listView.isHidden = false gridView.isHidden = true } else { listView.isHidden = true gridView.isHidden = false } }Useful operations:
insertSegment(withTitle:at:animated:)adds a segment.removeSegment(at:animated:)removes one.setTitle(_:forSegmentAt:)changes a title.selectedSegmentIndexidentifies the selected option.
A segmented control is most effective with a limited number of short, closely related options. It should not be used as a substitute for a long menu.
-
Question 14 of 20
Describe UISlider and show how its value can be converted into a percentage and displayed to the user.
Model answer
UISlider is a continuous control that allows the user to select a value by moving a thumb along a track. It is commonly used for volume, brightness, zoom, and playback position.
Important properties:
minimumValue: Lowest permitted value.maximumValue: Highest permitted value.value: Current selected value.minimumTrackTintColorandmaximumTrackTintColor: Customize track colors.thumbTintColor: Customizes the thumb.
If the slider's range is from
minimumValuetomaximumValue, its percentage is:Example:
Swiftslider.minimumValue = 0 slider.maximumValue = 1 slider.value = 0.5 slider.addTarget(self, action: #selector(sliderChanged), for: .valueChanged) @objc func sliderChanged(_ sender: UISlider) { let percentage = Int(sender.value * 100) valueLabel.text = "\(percentage)%" }For discrete values, the slider value can be rounded before use. Accessibility labels and values should be supplied so assistive technologies can report the setting.
-
Question 15 of 20
Explain UIAlertView and describe the recommended modern method for displaying an alert in iOS.
Model answer
UIAlertViewwas an older UIKit class used to show a modal alert containing a title, message, and buttons. It used a delegate to determine which button the user selected.UIAlertViewis deprecated and should not be used in modern applications. The recommended replacement isUIAlertControllerwith the.alertstyle.Modern example:
Swiftlet alert = UIAlertController( title: "Invalid Input", message: "Please enter all required values.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true)UIAlertController advantages:
- Uses action-handler closures instead of a delegate.
- Supports text fields.
- Handles default, cancel, and destructive actions.
- Provides both alert and action-sheet styles.
Alerts should communicate important information or request a decision. They should have concise messages and a limited number of clearly named actions.
-
Question 16 of 20
What is UIActionSheet? Explain its purpose and show how the same behavior is implemented using modern UIKit.
Model answer
UIActionSheetwas an older UIKit component that presented a list of choices related to the current context. It commonly included options such as Share, Delete, Choose Photo, and Cancel.UIActionSheetis deprecated. Modern applications useUIAlertControllerwith the.actionSheetstyle.Swiftlet sheet = UIAlertController( title: "Profile Photo", message: "Choose an action", preferredStyle: .actionSheet ) sheet.addAction(UIAlertAction(title: "Take Photo", style: .default) { _ in self.openCamera() }) sheet.addAction(UIAlertAction(title: "Delete Photo", style: .destructive) { _ in self.deletePhoto() }) sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(sheet, animated: true)On an iPad, an action sheet must be anchored using its
popoverPresentationController, for example to a source view or bar button item. Otherwise, the application may fail at runtime. Destructive actions should be clearly identified and used only when appropriate. -
Question 17 of 20
Compare an alert view and an action sheet with respect to purpose, presentation, and appropriate use.
Model answer
Both components request user attention, but they serve different purposes. In modern UIKit, both are created using
UIAlertControllerwith different preferred styles.Aspect Alert Action Sheet Style .alert.actionSheetPurpose Important message, warning, confirmation, or text input Selection from context-related actions Presentation Appears prominently in the center Usually appears from the bottom or as a popover Text fields Supported Not normally used or supported for this purpose Cancel action Optional but often appropriate Commonly included Typical example Confirming deletion or reporting invalid input Choosing Camera, Photo Library, or Remove Photo Guidelines:
- Use an alert when the user must acknowledge information or make a critical decision.
- Use an action sheet when presenting multiple actions for the current item.
- Use
.destructivefor irreversible operations such as deletion. - Avoid unnecessary interruptions and excessive numbers of actions.
- Configure the popover source when presenting an action sheet on an iPad.
The older
UIAlertViewandUIActionSheetclasses are deprecated. -
Question 18 of 20
Explain the purpose and operation of UIProgressView. How can progress be updated and animated?
Model answer
UIProgressView displays the completion status of a task as a horizontal progress bar. It is suitable for determinate operations such as file downloads, uploads, installations, or processing a known number of items.
The
progressvalue is a floating-point number in the range to , where means no progress and means completion.If
completedWorkout oftotalWorkunits has finished, progress is calculated as:Example:
SwiftprogressView.progress = 0 progressView.progressTintColor = .systemBlue progressView.trackTintColor = .systemGray5 let progress = Float(completedItems) / Float(totalItems) progressView.setProgress(progress, animated: true)Important considerations:
- Update UIKit controls on the main thread.
- Use
Progressor task callbacks to report real operation progress. - Hide or reset the view when the operation finishes.
- Use
UIActivityIndicatorViewinstead when the amount of work is unknown. - A nearby label can display a percentage such as
75%for greater clarity.
-
Question 19 of 20
Explain comprehensive keyboard handling in a form-based application, including dismissal, Return-key processing, and prevention of keyboard overlap.
Model answer
Keyboard handling ensures that users can enter data without the keyboard hiding the active control.
1. Dismissing the keyboard:
- Call
view.endEditing(true)when the user taps Done or outside an input. - For a text field, handle the Return key through
UITextFieldDelegate.
Swiftfunc textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true }2. Moving between fields:
- Set the Return key to
.nextfor intermediate fields and.donefor the last field. - In
textFieldShouldReturn, callbecomeFirstResponder()on the next field.
3. Preventing keyboard overlap:
- Place form controls inside a
UIScrollView. - Observe keyboard frame changes.
- Adjust the scroll view's bottom inset according to the keyboard intersection.
- Scroll the active input into view.
- Alternatively, use
keyboardLayoutGuideon supported iOS versions.
4. Accessory toolbar:
- Number pads have no Return key, so an
inputAccessoryViewwith a Done button can be added.
5. Cleanup and animation:
- Match layout updates to the keyboard's duration and animation curve.
- Remove notification observers when necessary.
Proper handling should account for safe areas, hardware keyboards, orientation changes, and varying keyboard sizes.
- Call
-
Question 20 of 20
Design a multi-view feedback application that uses UIKit controls, navigation, data passing, alerts, action sheets, and a progress view. Explain the complete flow.
Model answer
A feedback application can contain three screens: Feedback Form, Preview, and Submission Status.
1. Feedback Form screen:
UITextFieldfor the user's name and email.UITextViewfor multiline feedback.UISegmentedControlfor feedback category.UISliderfor a satisfaction rating.UISwitchfor permission to contact the user.UIImageViewand a button for attaching an image.
An action sheet can offer Camera, Photo Library, Remove Attachment, and Cancel actions.
2. Validation and navigation:
- When Preview is tapped, dismiss the keyboard.
- Validate required fields and email format.
- Present an alert if data is invalid.
- If valid, create a
Feedbackmodel and push the Preview controller.
Swiftoverride func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let preview = segue.destination as? PreviewViewController { preview.feedback = feedback } }3. Preview screen:
- Display the received data using labels and an image view.
- Allow the user to go back and edit or tap Submit.
- Use a delegate or closure if edited data must be returned.
4. Submission Status screen:
- Display
UIProgressViewwhile uploading the feedback and attachment. - Update progress on the main thread.
- At completion, set progress to and display a success alert.
- Provide a Done button to return to the initial screen.
Design requirements:
- Use a navigation controller for hierarchical movement.
- Apply Auto Layout and keyboard-safe scrolling.
- Keep network or storage logic outside the view controllers where possible.
- Handle failures with retry and cancel options.
- Add accessibility labels and avoid deprecated
UIAlertViewandUIActionSheetAPIs.
That's unit 3
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 3 of INT372 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 3 of INT372 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.