Reader small image

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product typeBook
Published inMay 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801813228
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

24. SwiftUI Lifecycle Event Modifiers

One of the key strengths of SwiftUI is that, through use of features such as views, state properties and observable objects, much of the work required in making sure an app handles lifecycle changes correctly is performed automatically.

It is still often necessary, however, to perform additional actions when certain lifecycle events occur. An app might, for example, need to perform a sequence of actions at the point that a view appears or disappears within a layout. Similarly, an app may need to execute some code each time a value changes, or to detect when a view becomes active or inactive. All of these requirements and more can be met by making use of a set of event modifiers provided by SwiftUI.

Since event modifiers are best understood when seen in action, this chapter will create a project which makes use of the three most commonly used modifiers.

24.1 Creating the LifecycleDemo Project

Launch Xcode and select the option to create a new Multiplatform App project named LifecycleDemo.

24.2 Designing the App

Begin by editing the ContentView.swift file and modifying the body declaration so that it reads as follows:

import SwiftUI

 

struct ContentView: View {

    

    var body: some View {

        TabView {

            TabView {

                FirstTabView()

                    .tabItem {

                        Image(systemName: "01.circle")

                        Text...

24.3 The onAppear and onDisappear Modifiers

The most basic and frequently used modifiers are onAppear() and onDisappear(). When applied to a view, these modifiers allow actions to be performed at the point that the view appears or disappears.

Within the FirstTabView.swift file, add both modifiers to the Text view as follows:

import SwiftUI

 

struct FirstTabView: View {

   

    var body: some View {

 

        Text("View One")

            .onAppear(perform: {

                print("onAppear triggered")

            })

            .onDisappear(perform: {

      ...

24.4 The onChange Modifier

In basic terms, the onChange() modifier should be used when an action needs to be performed each time a state changes within an app. This, for example, allows actions to be triggered each time the value of a state property changes. As we will explore later in the chapter, this modifier is also particularly useful when used in conjunction with the ScenePhase environment property.

To experience the onChange() modifier in action, begin by editing the SecondTabView.swift file so that it reads as follows:

import SwiftUI

 

struct SecondTabView: View {

    

    @State private var text: String = ""

    

    var body: some View {

        TextEditor(text: $text)

            .padding()

          ...

24.5 ScenePhase and the onChange Modifier

ScenePhase is an @Environment property which is used by SwiftUI to store the state of the current scene. When changes to ScenePhase are monitored by the onChange() modifier, an app is able to take action, for example, when the scene moves between the foreground and background or when it becomes active or inactive. This technique can be used on any view or scene, but is also useful when applied to the App declaration. For example, edit the LifecycleDemoApp.swift file and modify it so that it reads as follows:

import SwiftUI

 

@main

struct LifecycleDemoApp: App {

    

    @Environment(\.scenePhase) private var scenePhase

    

    var body: some Scene {

        WindowGroup {

            ContentView()

     ...

24.6 Summary

SwiftUI provides a collection of modifiers designed to allow actions to be taken in the event of lifecycle changes occurring in a running app. The onAppear() and onDisappear() modifiers can be used to perform actions when a view appears or disappears from view within a user interface layout. The onChange() modifier, on the other hand, is useful for performing tasks each time the value assigned to a property changes.

The ScenePhase environment property, when used with the onChange() modifier, allows an app to identify when the state of a scene changes. This is of particular use when an app needs to know when it moves between foreground and background modes.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801813228
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth