Unit 3: UIKit Controls

INT372 — Iphone Application Programming 9 min read

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 UIViewController manages a screen’s views, lifecycle, navigation, and user interactions.
  • Target–action pattern: Controls such as UIButton, UISwitch, and UISlider send events to registered action methods.
  • Delegation: Objects such as UITextField use delegates to report editing events and request decisions.
  • Outlets and actions:
    • @IBOutlet connects storyboard objects to code.
    • @IBAction connects 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, and configuration.
  • Event handling: Register a method for an event such as .touchUpInside.
SWIFT
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, and isScrollEnabled control content and behavior.
  • Delegation: UITextViewDelegate methods detect editing and text changes.
  • Keyboard dismissal: Call resignFirstResponder() on the active text view or view.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.
SWIFT
override func touchesBegan(_ touches: Set<UITouch>,
                           with event: UIEvent?) {
    view.endEditing(true)
}
  • Modern layout aid: view.keyboardLayoutGuide can 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: keyboardType selects keyboards such as .numberPad, .emailAddress, or .phonePad.
  • Content hints: textContentType supports AutoFill for values such as names, email addresses, and passwords.
  • Security: isSecureTextEntry = true hides password characters.
  • Customization: Set placeholder, borderStyle, clearButtonMode, leftView, and rightView.
  • Custom input views: Assign a picker or another view to inputView; assign controls such as Done to inputAccessoryView.
  • Validation: Use UITextFieldDelegate to restrict characters or respond to Return.
SWIFT
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

D. UISwitch

A UISwitch represents a two-state choice such as enabled/disabled.

  • State: Read isOn or change it using setOn(_:animated:).
  • Event: Handle .valueChanged whenever the user changes the state.
  • Meaning: Place a text label beside the switch because the switch itself should represent only the Boolean value.
SWIFT
@IBAction func notificationsChanged(_ sender: UISwitch) {
    notificationsEnabled = sender.isOn
}
  • Persistence: A preference can be stored in UserDefaults, for example with set(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 and UIImage(systemName:) for symbols.
  • Scaling: contentMode = .scaleAspectFit preserves the entire image; .scaleAspectFill fills the bounds but may crop it.
  • Clipping: Set clipsToBounds = true when using aspect fill or rounded corners.
  • Interaction: isUserInteractionEnabled is false by 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 UIImageView for a profile image, UITextField for a name, UITextView for a biography, UISwitch for notifications, and UIButton for saving.
  • Processing sequence:
    1. Read nameField.text and bioTextView.text.
    2. Check notificationSwitch.isOn.
    3. Validate required input.
    4. Update the model and display confirmation.
  • Separation: The controls present and collect data; a model structure should store the resulting values.
  • Layout: Place content in a UIScrollView or 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: frame is expressed in the superview’s coordinates, while bounds describes 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.
SWIFT
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: UINavigationController supports hierarchical movement, while UITabBarController provides 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.
SWIFT
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.

  1. Forward passing:
    • Property injection: Set a destination property before pushing or presenting.
    • Segue preparation: Access segue.destination in prepare(for:sender:).
SWIFT
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let details = segue.destination as? DetailsViewController {
        details.itemName = selectedName
    }
}
  1. 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: selectedSegmentIndex identifies the chosen segment; UISegmentedControl.noSegment represents no selection.
  • Configuration: Segments may contain short titles or images.
  • Event: Handle .valueChanged to 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: minimumValue and maximumValue define limits; value stores the current Float.
  • Event behavior: .valueChanged fires continuously unless isContinuous is disabled.
  • Example: For volume, use a range from 0.0 to 1.0.
SWIFT
@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 UIAlertController with preferred style .alert.
  • Actions: Add UIAlertAction objects for choices such as OK, Cancel, or Delete.
  • Purpose: Alerts should communicate important information or request a decision without unnecessary interruption.
SWIFT
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 UIAlertController with preferredStyle: .actionSheet.
  • Action roles: Use .default for normal operations, .destructive for irreversible operations, and .cancel for dismissal.
  • iPad requirement: Configure the controller’s popoverPresentationController with 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 progress property is a Float from 0.0 to 1.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.
SWIFT
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.