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

iOS Development - SwiftUI Basics

Stuttgart Media University

1 Agenda

  • What is SwiftUI?
  • Why SwiftUI?
  • Declarative Programming in SwiftUI
  • Key Characteristics of SwiftUI Views
  • State Management in SwiftUI
  • Built-in Components and Customization
  • Interoperability with UIKit
  • Animation and Interaction
  • Adaptive Design for multiple platforms
  • Getting Started with SwiftUI
  • Toolset
  • Conclusion

2 What is SwiftUI?

  • SwiftUI was introduced with iOS 13 in autumn 2019 and only runs on iOS 13 (or above) devices
  • Next to StoryBoards SwiftUI allows to define the User Interface (UI) of your app
  • In contrast to StoryBoards where the UI is defined using a WYSIWYG editor, SwiftUI allows you to code your UI in Swift
  • It is a declarative way of defining a UI, similar to what other frameworks such as Jetpack Compose (in Kotlin) for Android, Flutter (Google) and React (Facebook) do

3 Why SwiftUI?

  • Pros of SwiftUI in comparison with StoryBoards
    • StoryBoards can become very complex and large, this can lead to confusion and slow loading times
    • The XML code of StoryBoards is generated, making it hard to control whats going on in detail
    • The separation between UI and code makes it sometimes complicated to add dynamic behavior to components
    • It is sometimes easier to declare everything in one place and in one language and being independent of a WYSIWIG editor
    • ...put your pro here

4 Why SwiftUI?

  • Drawbacks of SwiftUI
    • Sometimes a separation between code and UI is helpful in a team with different responsibilities
    • A designer needs to work with Swift code and StoryBoards is easier to use for non programmers
    • Complex UIs in SwiftUI can become also very diffcult to understand in code
    • ...put your drawback here

SwiftUI is just another option of defining your UI. It does not replace UIKit and depending on your requirements it may or may not be the better option to use for your app. Before StoryBoards, there was a discussion between the Objective-C enthusiasts who would only programmatically develop their UI and the others who did it using Interface Builder. Now this discussion may return, but differently.

5 Declarative Programming in SwiftUI

  • Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow
  • It allows developers to describe the desired UI outcome, while SwiftUI handles the implementation details

Example of a declarative code in SwiftUI:

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
    }
}
  • Swiftui uses structs instead of classes because they are value types and more efficient

5.1 Difference between declarative and imperative programming

  • While declarative programming describes the outcome, imperative programming requires specifying each step manually

Example for imperative programming:

let label = UILabel()
label.text = "Hello, World!"
Declarative Programming Imperative Programming
Describes the outcome Specifies each step
Focuses on what to do Focuses on how to do
Easier to read and maintain More verbose and complex
More efficient and scalable Less efficient and harder to scale

5.2 Other examples of frameworks that use declarative programming:

6 Key Characteristics of SwiftUI Views

SwiftUI Views are:

  • Declarative, that is, they describe the desired UI state
  • Compositional, that is they are built from simple components
  • State-driven views, that is, they update based on changes in the app's state
  • Value types (structs) for efficiency

6.1 Example of a Declarative nature

  • Describing the UI in terms of its desired state
struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

6.2 Example of State-driven

  • Updating the UI based on changes in the app's state
struct ContentView: View {
    @State private var isTapped = false

    var body: some View {
        Button(action: {
            self.isTapped.toggle()
        }) {
            Text(isTapped ? "Tapped" : "Not Tapped")
        }
    }
}

6.3 Example of Compositional Design

  • Building complex UIs from simple components
struct ContentView: View {
    var body: some View {
        VStack {  // Vertical stack component
            Text("Hello, World!") // Text component
            Button("Tap Me") { // Button component
                print("Button was tapped")
            }
        }
    }
}

6.4 Example for view modifiers

  • Changing the design using view modifiers
struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .font(.title) // Modifying the font
            .foregroundColor(.blue) // Modifying the text color
    }
}

7 State Management in SwiftUI

State management is a key concept in SwiftUI that allows to manage the state of the UI and update it based on changes in the app's state. SwiftUI provides tools for managing state, such as State, Binding, and Observable objects:

  • State is a property wrapper that allows a view to store and update its own state
  • Binding is a property wrapper that creates a two-way connection between a view and its underlying data
  • Observable objects are objects that can be observed for changes

More information on State and Bindings can be found here

8 Built-in Components and Customization

  • SwiftUI defines multiple simple UI components that you can use
  • The protocol View defines methods and properties (e.g. body) with default implementations, that all basic SwiftUI types conform to. You can create custom Views that conform to the View protocol
  • Basic SwiftUI component types (structs) are, e.g.:
    • Text, TextField, SecureField
    • Image
    • Button
    • Slider, Stepper
    • Lists, ScollView, Form, Group and many more...

9 Working with Views

  • You can easily add view components to your View by selecting from the Library and drag&dropping them on the code, as shown here:

center 50%

10 Compositional Design

SwiftUI code reflects the hierarchy of views, making it easy to organize UI components. Compositional design helps maintain clean, modular, and reusable code by breaking down complex UIs into simple components.

  • For the layout of your Views you can use View components such as:

    • HStack - a view that arranges its children in a horizontal line
    • VStack - arranges children in a vertical line
    • ZStack - overlays its children, aligning them in both axes
  • For Navigation between views you can use:

    • NavigationView
    • TabView
    • HSplitView, VSplitView
    • Alert - shows an alert presentation

11 Interoperability with UIKit

  • SwiftUI also supports integration of UIKit views easily using the UIViewRepresentable protocol. All you need to implement is a makeUIView(context:) and the updateUIView(_:context:) methods e.g. as shown here:
struct MapView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ uiView: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(
            latitude: 34.011286, longitude: -116.166868)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        uiView.setRegion(region, animated: true)
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}

12 Animation and Interaction

SwiftUI provides tools for adding animations and interactions to your app:

struct ContentView: View {
    @State private var isTapped = false

    var body: some View {
        Button(action: {
            withAnimation {
                self.isTapped.toggle()
            }
        }) {
            Text(isTapped ? "Tapped" : "Not Tapped")
        }
    }
}

13 Adaptive Design for multiple platforms

  • SwiftUI views adapt to different Apple platforms (iOS, macOS, watchOS, tvOS)
  • Built-in support for dark mode, accessibility features, localization, and more
  • This allows to write code once, that automatically adapts across multiple platforms

14 Getting Started with SwiftUI

Exploring SwiftUI tutorials, documentation, and learning resources

Please start with the following resources:

Then continue with:

15 Toolset

  • When you want to use SwiftUI, you need to select SwiftUI instead of StoryBoards as "User Interface"

center 50%

16 Toolset

  • Your project will then contain a ContentView.swift file as shown here
  • Xcode (since version 11.4.) provides a new SwiftUI preview (called Canvas) that will show the rendered content of your view. You may need to press the "Resume" button once to start it.

center 50%

17 Conclusion

  • SwiftUI is a powerful tool for building native, engaging apps
  • SwiftUI offers even more functionality but basically it is just another way (declarative instead of imperative) to create your UI and not a replacement for UIKit

Recap of SwiftUI's key features and advantages:

  • Declarative programming
  • Compositional design
  • State management
  • Interoperability with UIKit
  • Adaptive design for multiple platforms
  • Animation and interaction support
  • SwiftUI preview in Xcode
  • SwiftUI is a great choice for building modern, responsive, and scalable apps