SwiftUI | View Life Cycles
Learn from Examples.
The Basics
Before we get started, I would like to talk about Views and View Controllers. Views are basically objects that can be drawn on the screen such as Texts, Buttons, Navigations Views, Labels, and etc. View Controllers on the other hand, are classes that handle the state and functions of a view. Views listen to the events of the view controllers and act accordingly. The view controller is also responsible for determining at what particular time the view will appear and disappear from the screen.
If you have used UIKit, you would be familiar with the following diagram which determines the different lifecycles of a view. If not, don’t worry, SwiftUI does not use these lifecycles.
SwiftUI LifeCycles
SwiftUI does not have a View Controller, and like I have mentioned before, does not use the standard lifecycles that Apple offered with UIKit. Instead, SwiftUI uses .onAppear and .onDissapear methods. Before we dig in, let’s look at the official definition provided by Apple.
.onAppear(perform:)
Adds an action to perform when the view appears — Apple
.onDissapear(perform:)
Adds an action to perform when the view disappears -Apple
SwiftUI LifeCycle Examples
There is one important thing to note about lifeCycles in SwiftUI. Navigation views act a little funky when it you implement the .onDissapear method. You would expect the view to call the .onDissapear method when you navigate to navigationLink but it doesn’t.
If you think about it, the navigationLink is still inside of the navigationView, so we are not necessarily leaving the main view. When we run this into our simulator, “Main View onDissapear” will never be printed on the console. Even if we leave the application.
Now that we have got things covered lets start from the beggining. Once we run the code, the simulator will show the ContentView, which looks something like this.
The console will print the following
Main View onAppearnavigation Text onAppear
Now, lets look at the code snippet for navigationView1.
Once we we click on the navigationLink (“Go to navigationView1”) the simulator looks something like this.
The console prints out the following. Keep in mind that we have only implemented .onAppear and .onDissapear for “Hello World3”.
Hello World onAppear
navigationView1 onAppear
navigation Text onDissapear
Finally when we go back, the console prints out the following.
navigation Text onAppear
Hello World onDissapear
navigationView1 onDissapear
That is all for today. I really hope this example helped you understand the concept of LifeCycles in SwiftUI. If you have any questions feel free to email me at yu24c@mtholyoke.edu.