Unit 3: UIKit Controls
I. UIKit Foundations
UIKit is Apple’s event-driven user-interface framework for iPhone applications. It supplies views, controls, view controllers, navigation mechanisms, and feedback components. UIKit objects are generally created in a storyboard or programmatically, configured during a view controller’s lifecycle, and updated on the main thread.
A. Defining Characteristics
UIKit development depends on a hierarchy of views, event-handling mechanisms, and view controllers that coordinate presentation and application logic.
- View hierarchy: Every visible interface element derives from
UIView; child views are arranged inside parent views. - View controllers: A
UIViewControllermanages a screen’s views, lifecycle, navigation, and user interactions. - Target–action pattern: Controls such as
UIButton,UISwitch, andUISlidersend events to registered action methods. - Delegation: Objects such as
UITextFielduse delegates to report editing events and request decisions. - Outlets and actions:
@IBOutletconnects storyboard objects to code.@IBActionconnects control events to methods.
- Auto Layout: Constraints define position and size relative to safe areas, margins, and neighboring views.
- Main-thread rule: UI creation and updates must occur on the main thread.
- Lifecycle:
viewDidLoad()is commonly used for initial setup after a controller’s view has loaded.
II. Basic Input and Display Controls
These controls accept taps or text, represent Boolean states, and display images. Their properties define appearance, while events and delegates determine behavior.
A. Implementing UIButton
A UIButton performs an action when the user taps it.
- Creation: Add the button in Interface Builder or instantiate
UIButton(type: .system). - Configuration: Use
setTitle(_:for:),setImage(_:for:),tintColor, andconfiguration. - Event handling: Register a method for an event such as
.touchUpInside.
let saveButton = UIButton(type: .system)
saveButton.setTitle("Save", for: .normal)
saveButton.addTarget(self,
action: #selector(saveTapped),
for: .touchUpInside)
@objc private func saveTapped() {
print("Saved")
}- State support: A button can display different titles or images for
.normal,.highlighted,.selected, and.disabled. - Accessibility: Use a clear title or
accessibilityLabel, especially for image-only buttons.
B. UITextView and keyboard handling
A UITextView supports editable, scrollable, multiline text and requires keyboard management to prevent obscured content.
- Core properties:
text,font,textColor,isEditable, andisScrollEnabledcontrol content and behavior. - Delegation:
UITextViewDelegatemethods detect editing and text changes. - Keyboard dismissal: Call
resignFirstResponder()on the active text view orview.endEditing(true)on its container. - Keyboard overlap: Observe keyboard frame notifications and adjust a scroll view’s inset or bottom constraint.
- Return behavior: Unlike a text field, pressing Return normally inserts a new line.
override func touchesBegan(_ touches: Set<UITouch>,
with event: UIEvent?) {
view.endEditing(true)
}- Modern layout aid:
view.keyboardLayoutGuidecan constrain content above the keyboard without manually calculating keyboard height.
C. UITextField and customizing inputs
A UITextField accepts a single line of text and can be customized for specific data-entry tasks.
- Input configuration:
keyboardTypeselects keyboards such as.numberPad,.emailAddress, or.phonePad. - Content hints:
textContentTypesupports AutoFill for values such as names, email addresses, and passwords. - Security:
isSecureTextEntry = truehides password characters. - Customization: Set
placeholder,borderStyle,clearButtonMode,leftView, andrightView. - Custom input views: Assign a picker or another view to
inputView; assign controls such as Done toinputAccessoryView. - Validation: Use
UITextFieldDelegateto restrict characters or respond to Return.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}D. UISwitch
A UISwitch represents a two-state choice such as enabled/disabled.
- State: Read
isOnor change it usingsetOn(_:animated:). - Event: Handle
.valueChangedwhenever the user changes the state. - Meaning: Place a text label beside the switch because the switch itself should represent only the Boolean value.
@IBAction func notificationsChanged(_ sender: UISwitch) {
notificationsEnabled = sender.isOn
}- Persistence: A preference can be stored in
UserDefaults, for example withset(sender.isOn, forKey: "notifications").
E. UIImageView
A UIImageView displays a UIImage, including asset-catalog images and SF Symbols.
- Image loading: Use
UIImage(named:)for assets andUIImage(systemName:)for symbols. - Scaling:
contentMode = .scaleAspectFitpreserves the entire image;.scaleAspectFillfills the bounds but may crop it. - Clipping: Set
clipsToBounds = truewhen using aspect fill or rounded corners. - Interaction:
isUserInteractionEnabledisfalseby default; enable it before attaching gestures. - Efficiency: Resize large images appropriately instead of displaying unnecessarily high-resolution files.
F. Creating small application with these controls
A small settings/profile application can combine text, images, buttons, and Boolean controls through target–action and outlets.
- Interface: Use an
UIImageViewfor a profile image,UITextFieldfor a name,UITextViewfor a biography,UISwitchfor notifications, andUIButtonfor saving. - Processing sequence:
- Read
nameField.textandbioTextView.text. - Check
notificationSwitch.isOn. - Validate required input.
- Update the model and display confirmation.
- Read
- Separation: The controls present and collect data; a model structure should store the resulting values.
- Layout: Place content in a
UIScrollViewor stack view so it remains usable with different screen sizes and the keyboard.
III. Views and Multi-Screen Navigation
UIKit applications organize controls inside views and use view controllers, segues, and navigation controllers to move between screens.
A. Understanding and working with views
A UIView is a rectangular interface region responsible for layout, appearance, and interaction.
- Geometry:
frameis expressed in the superview’s coordinates, whileboundsdescribes the view’s internal coordinate system. - Hierarchy:
addSubview(_:)inserts a child;removeFromSuperview()removes it. - Appearance:
backgroundColor,alpha,isHidden, and layer properties control presentation. - Layout: Auto Layout constraints are preferred over fixed coordinates because device dimensions and safe areas vary.
- Interaction: Gesture recognizers add tap, swipe, pan, pinch, or long-press behavior.
- Animation: Changes to animatable properties can be enclosed in
UIView.animate.
UIView.animate(withDuration: 0.3) {
self.panelView.alpha = 1.0
}B. Multi-view applications
A multi-view application separates features across multiple view controllers rather than placing the entire interface on one screen.
- Structure: Each view controller should manage one coherent task, such as listing products or editing a profile.
- Containers:
UINavigationControllersupports hierarchical movement, whileUITabBarControllerprovides parallel top-level sections. - Lifecycle events:
viewWillAppear(_:)is useful for refreshing information whenever a screen becomes visible. - Memory and ownership: Controllers should avoid strong reference cycles, particularly in closures and delegate relationships.
C. Concept of segue
A segue is a storyboard-defined transition from one view controller to another.
- Triggering: A segue can originate from a control or be invoked with
performSegue(withIdentifier:sender:). - Identifier: A unique string distinguishes transitions, such as
"showDetails". - Preparation:
prepare(for:sender:)configures the destination before presentation. - Types: Common transitions include Show, Show Detail, and Present Modally.
- Limitation: Segues are storyboard-oriented; fully programmatic interfaces typically instantiate and present controllers directly.
D. Calling another view controller using navigation controller
A navigation controller calls another screen by pushing it onto a stack.
- Push operation:
pushViewController(_:animated:)places the destination above the current controller. - Back operation: The navigation controller automatically supplies a Back button;
popViewController(animated:)removes the top controller. - Requirement: The source must be embedded in a
UINavigationController.
let details = DetailsViewController()
navigationController?.pushViewController(details, animated: true)- Modal alternative: Use
present(_:animated:)when the new screen represents a separate task rather than the next hierarchical level.
E. Passing and receiving data in view controllers
Data should be assigned to the destination before navigation and returned through controlled communication patterns.
- Forward passing:
- Property injection: Set a destination property before pushing or presenting.
- Segue preparation: Access
segue.destinationinprepare(for:sender:).
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let details = segue.destination as? DetailsViewController {
details.itemName = selectedName
}
}- Returning data:
- Delegate: Define a protocol and call the delegate when data changes.
- Closure: Assign a callback closure before navigation.
- Shared model: Use a model object when several controllers operate on the same state.
- Safety: Avoid depending on destination outlets before its view has loaded; pass model data into ordinary properties instead.
IV. Selection, Alerts, and Progress Controls
These controls select among options, adjust numeric values, communicate decisions, and display task completion.
A. UISegmentedControl
A UISegmentedControl presents a compact set of mutually exclusive choices.
- Selection:
selectedSegmentIndexidentifies the chosen segment;UISegmentedControl.noSegmentrepresents no selection. - Configuration: Segments may contain short titles or images.
- Event: Handle
.valueChangedto filter or switch displayed content. - Constraint: Use only a small number of closely related choices; long labels reduce readability.
B. UISlider
A UISlider allows continuous selection of a numeric value within a range.
- Range:
minimumValueandmaximumValuedefine limits;valuestores the currentFloat. - Event behavior:
.valueChangedfires continuously unlessisContinuousis disabled. - Example: For volume, use a range from
0.0to1.0.
@IBAction func volumeChanged(_ sender: UISlider) {
volumeLabel.text = String(format: "%.0f%%", sender.value * 100)
}- Accessibility: Provide a label or value description that explains the quantity being adjusted.
C. UIAlertView
UIAlertView was an older class for displaying alert messages, but it has been deprecated since iOS 9.
- Modern replacement: Use
UIAlertControllerwith preferred style.alert. - Actions: Add
UIAlertActionobjects for choices such as OK, Cancel, or Delete. - Purpose: Alerts should communicate important information or request a decision without unnecessary interruption.
let alert = UIAlertController(title: "Saved",
message: "Profile updated.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true)D. UIActionSheet
UIActionSheet was used for presenting related actions, but it is deprecated and replaced by UIAlertController.
- Modern style: Create
UIAlertControllerwithpreferredStyle: .actionSheet. - Action roles: Use
.defaultfor normal operations,.destructivefor irreversible operations, and.cancelfor dismissal. - iPad requirement: Configure the controller’s
popoverPresentationControllerwith a source view or bar-button item to prevent presentation errors. - Use case: An image screen may offer “Take Photo,” “Choose Photo,” and “Cancel.”
E. Progress View
A UIProgressView displays the completion level of a determinate operation.
- Progress range: The
progressproperty is aFloatfrom0.0to1.0. - Animated update:
setProgress(_:animated:)visually moves the progress bar. - Concrete value: If 30 of 100 files are processed, progress is
30 / 100 = 0.3. - Threading: Background work may calculate progress, but visual updates must return to the main thread.
DispatchQueue.main.async {
self.progressView.setProgress(0.3, animated: true)
}- Limitation: Use an activity indicator rather than a progress view when the total amount of work is unknown.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. 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. Chip in only if it was worth it. What it pays for →