Open menu with table of contents iOS Development - UIKit Basics
Logo of Stuttgart Media University for light theme Logo of Stuttgart Media University for dark theme
Mobile Application Development 2

iOS Development - UIKit Basics

Stuttgart Media University

1 Agenda

  • App Components
    • User Interface
      • Interface Builder
      • StoryBoards
      • Autolayout
    • Application Logic
      • AppDelegate, SceneDelegate, UIViewController
    • Model
      • Core Data
  • References

2 iOS App Components

  • iOS makes use the Model View Controller-Design Pattern (to be more specific Model-View-Presenter)
  • User interfaces can be defined in XML files (.xib or .storyboard) using Interface Builder or by using the SwiftUI Framework in code
  • The app life-cycle is controlled in classes implementing the UIApplicationDelegate / UISceneDelegate protocols
  • Business-logic is defined in UIViewController derived (in the case of UIKit usage) and/or other classes
  • iOS provides CoreData for the data model (contained in .xcdatamodel file) or SwiftData when using SwitUI, but also custom classes can be used

3 iOS Project Files

In a StoryBoard based project with Swift and CoreData the project structure looks like this:

65% center

4 Interface Builder

  • The Interface Builder is a tool in Xcode to define app-screens (Views) and interactions when using StoryBoards
    • XIBs are single views
    • Storyboards can contain multiple views and segues that define the transition between views
    • It allows to define View Component interactions using IBActions and IBOutlets
      • Outlets connect the visual representation (View Component) with the source code, allowing to access a component from source
      • Actions trigger method calls on certain events, e.g. button tapped

5 XIB

  • Defines the view of one screen

center

6 Storyboards

  • Allows to define views and segues (including transitions) graphically in Interface Builder

  • StoryBoards are ideal for rapid prototyping

  • Following main types of segues exist, see Apple documentation:

    • Show - is used within a view managed by a NavigationController
    • Present Modally - Displays the view controller modally using the specified presentation and transition styles
    • Show Detail (Replace) - is used within a UISplitViewController, if not shows a modal popover
    • Present as Popover - in a horizontally regular environment, UIKit presents the view controller in a popover. In a horizontally compact environment, UIKit presents the view controller modally
    • Custom - requires own implementation of UIStoryboardSegue class. Can be used with NavigationController

80%

7 Autolayout

  • Since the first iPhone multiple devices with different resolutions where introduced, such as for example:
    • iPhone 4 / 4s: 960 x 640 pixels
    • iPhone 5/5c/5s: 1136 x 64 pixels
    • iPhone 6/6s/7/8: 1334 x 750 pixels
    • iPhone 6 Plus/6s/7/8 Plus: 1920 x 1080 pixels
    • iPhone Xs: 2436 x 1125 pixels
    • iPhone Xs Max: 2688 x 1242 pixels
    • iPad Mini / iPad 2: 1024 x 768 pixels
    • iPad Air / iPad / iPad Mini: 2048 x 1536
    • iPad Pro 12.9'': 2732 x 2048 pixels
    • Apple Watch Series 4: 368 x 448 pixels (44 mm), 324 x 394 pixels (40mm)

8 Autolayout

  • AutoLayout tries to facilitate the UI design for all the different device resolutions and screen sizes
  • It allows to design the app UI layout in a device independent fashion using constraints
  • Constraints define how the size and position of controls / views behave within a view when the resolution or orientation of the device changes
  • Interface Builder provides corresponding tools to define the constraints for each view

8.1 Autolayout Tools in Xcode

center 50%

8.2 Size Classes

  • Introduced with iOS 8 to allow using one storyboard for universal apps
  • Two types: vertical and horizontal, each with the sizes Regular, Compact or Any
  • Size classes correspond to the device and orientation the app runs in
  • You can design individual layouts for each device class by selecting it in Interface Builder here

center 40%

8.3 Simulated Metrics & Stack View

  • To directly see the effects of the constraints on different devices, select the view controller and change to the corresponding device under „Simulated Metrics“
  • When you select multiple views (e.g. a label and a button) and then click on the „Stack“ icon, the views are added to a Stack View
  • Stack Views can be horizontally or vertically oriented
  • Views within a Stack View are similar to LinearLayouts on Android

8.4 Stack View

  • The layout of the views within a StackView (class UIStackView) varies depending on the axis (horizontal or vertical), distribution, alignment and spacing
  • You can set the properties in the attributes inspector

center 60%

source

8.5 Pin

  • The „Pin“ function allows to define the spacing and size of views
  • For example the spacing to the nearest neighbor
  • When multiple views are selected, it is possible to set them, e.g. to equal width or height and to define their relative alignment
  • The size can be also defined in an aspect ratio (width:height)

50%

8.6 Alignment

The „Alignment“ function allows to define the alignment of views relative to each other Views can be aligned vertically or horizontally to their centers They can be aligned according their baselines Or horizontally or vertically in their superview

50%

8.7 Issue Solver

  • Constraint issues can be solved using the „issue solver“ button in the bottom right corner
  • They are either warnings (orange color)
  • Or errors (red color)
  • Xcode can try to automatically add missing constraints or ask you to remove contradictory constraints

center 20%

9 UI Components

  • UI Components are the building blocks of your UI. There are many different components you can choose from such as:
    • Label, Button, Segment Control, Text Field, Slider, Switch, Activity Indicator, Progress View, Page Control, Stepper, Table View, Table View Cell, Image View
  • All UI components extend the view class. You can extend the View class yourself or another View based component to create a custom view
  • View components work together with View Controller classes such as:
    • ViewController, NavigationController, TableViewController, TabBarController
  • In order to create your UI in Storyboards just select the components you want and add them to the Storyboard

10 UIKit

  • Provides basic classes and functions to construct and manage iOS apps, e.g.:
    • View & Window
    • View Controller
    • Multitouch handling
    • Apps foreground & background execution using the AppDelegate

11 UIView & UIWindow

  • Views are used to represent contents on a screen
  • A view is an instance of the class UIView (or subclass)
    • UIView manages a rectangular area in the application window
    • Is responsible for drawing content, handling multitouch-events and managing the layout of its subviews
  • A Window is an instance of the UIWindow class. It handles the overall UI of the application and works with the views it contains
  • Every application has at least one Window and if a second screen is connected it can have two

12 UIView & UIWindow

  • Architecture of Views in a sample application

center

Source

13 Core Animation

  • Uses „layer“ objects that render the content of your view into a bitmap
  • Layers can be easily animated using full power of the graphics hardware
  • Animations modify the properties of the layer over time
  • You can use it to change the opacity, the position andthe size and orientation of the layer on screen

14 The App Delegate

  • Every Application has an AppDelegate that is initialized when the App starts
  • It provides the methods to handle the different application states
  • The AppDelegate also initializes the Window for the App and sets the RootViewController (including the first view that is shown)

15 AppDelegate Methods

  • The AppDelegate implements the UIApplicationDelegateProtocol and defines the starting point of your app (application(.. didFinishLauchingWithOptions ...))
  • Since iOS 13 it also starts or discards a UISceneSession - an abstraction to be able to have multiple "windows" in an app at the same time
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

// MARK: UISceneSession Lifecycle

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

16 SceneDelegate Methods

  • The SceneDelegate takes over most of the functionality of the AppDelegate from iOS 13 on
  • It has a reference to the window and implements the different life-cycle methods such as, e.g.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {}
func sceneDidDisconnect(_ scene: UIScene) {}
func sceneDidBecomeActive(_ scene: UIScene) {}
func sceneWillResignActive(_ scene: UIScene) {}
func sceneWillEnterForeground(_ scene: UIScene) {}
func sceneDidEnterBackground(_ scene: UIScene) {}

17 UIViewController

  • Example UIViewController implementation
import UIKit // UIViewController is part of the UIKit Framework

class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!

    override func viewDidLoad() { // called when the view becomes visible
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func viewWillAppear(_ animated: Bool) {
        // This is called shortly before the view is visible
    }
    override func viewDidAppear(_ animated: Bool) {
        // This is called when the view is visible and users can interact with it
    }
    override func viewWillDisappear(_ animated: Bool) {
        // Is called before the transition to the next view controller
    }
    override func viewDidDisappear(_ animated: Bool) {
        // is called when view is not visible anymore
    }
    override func didReceiveMemoryWarning() {
        // Called when memory is low
    }
    @IBAction func buttonTouched(sender: UIButton) { // custom action method
        myLabel.text = "Hello Swift"
    }
}

18 Multi-Touch Event Handling

  • To handle multi-touch events, e.g. the following methods can be implemented in your ViewController
override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
    print("touches began")
}

override func touchesEnded(_: Set<UITouch>, with: UIEvent?){
    print("touches ended")
}

override func touchesMoved(_: Set<UITouch>, with: UIEvent?){
    print("touches moved")
}
override func touchesCancelled(_: Set<UITouch>, with: UIEvent?){
    print("touches cancelled")
}

19 Event Handling

  • UIEvents are created and delivered to the different components of your app like shown here:

center

Source

20 UIResponder

  • UIResponder class and responder objects can handle UIEvents.
  • Left side iOS, right side MacOS

center

Source

21 First Responder

  • First view in a window to receive the following type of events and messages:
    • Motion events: user shakes the device
    • Remote-control events: event from head-set or other accessory
    • Action messages: user presses a button or changes a slider and no target is specified for the action message
    • Editing-menu messages: user taps the commands of the editing menu

22 Responder Chain

  • The responder chain enables cooperative event handling
  • If the first responder cannot handle an event it forwards it to the "next responder"

center 60%

Source

23 Control Objects Event Handling

  • Subclasses of UIControl (called control objects) already implement multi-touch event handling, e.g.
    • UIButton, UISlider
  • They are receptive to certain type of gestures, e.g. tapping or dragging
  • They can be configured to send an action to a target object when that gesture occurs
  • Event connections can be used to connect a control object with a target object

24 UITextField

  • UITextField Class can be used to enter text
  • When the user clicks on it the soft-keyboard is shown
  • To close the keyboard when the „return“-key is pressed, you need to add an action method and call following method on the TextField:
@IBAction func returnPressed(sender: AnyObject) {
    myTextField.resignFirstResponder()
}

25 Core Data

  • Provides object-relational mapping (ORM)
  • Xcode includes a data model editor for core data

center 70%