SwiftUI Life Cycle

Shashidhar Jagatap
4 min readDec 23, 2023

--

SwiftUI is a modern and declarative framework developed by Apple for building user interfaces across various Apple platforms, including iOS, macOS, watchOS, and tvOS. Its declarative syntax simplifies UI development by allowing developers to describe the desired interface and behavior, and SwiftUI takes care of the rest. This framework utilizes a reactive programming paradigm, making it highly efficient for creating interactive and responsive applications. SwiftUI leverages its lifecycle management to handle changes in the state of the app, ensuring a seamless user experience.

Lifecycle Stages in SwiftUI

SwiftUI follows a series of lifecycle stages that manage the behavior and appearance of its views, ensuring proper state management and updates. These stages are fundamental in understanding how views are created, updated, and removed within an app.

  1. Initialisation:

Description: During initialisation, SwiftUI views are created and prepared but not yet displayed. Here, you can set up initial properties and configurations for the view.
This marks the birth of a SwiftUI view. Initialisation involves setting up initial properties, data structures, or configuring the view before it’s displayed.

Example: When creating a new SwiftUI View, the init() method is used for setting up initial properties or performing any required setup.

struct ContentView: View {
var myText: String

init() {
// Perform setup or initialization here
myText = "Welcome to SwiftUI!"
}

var body: some View {
Text(myText)
}
}

2. Appear/Disappear:

  • Description: Views go through transitions of appearing and disappearing on the screen. The onAppear() and onDisappear() modifiers allow executing code when the view enters or exits the screen, facilitating actions tied to visibility changes.
  • Example: Executing specific actions when a view appears or disappears, like loading data or stopping animations.
struct ContentView: View {
@State private var timerRunning = false
@State private var counter = 0

var body: some View {
VStack {
Text("Timer: \(counter)")
.font(.title)

Spacer()
}
.onAppear {
// Code executed when view appears
startTimer()
}
.onDisappear {
// Code executed when view disappears
stopTimer()
}
}

func startTimer() {
timerRunning = true
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
counter += 1
}
}

func stopTimer() {
timerRunning = false
}
}

3. Updating:

  • Description: SwiftUI views are updated when their underlying state changes. Properties marked with @State, @Binding, or @ObservableObject trigger view updates.
  • Example: Updating UI elements based on changes in state, such as modifying text or color dynamically.
import SwiftUI

// Example of a simple counter view
struct CounterView: View {
// @State property wrapper for managing internal state
@State private var counter = 0

var body: some View {
VStack {
Text("Counter: \(counter)")
.font(.headline)

// Button to increment counter value
Button("Increment") {
// Updating @State property triggers view update
counter += 1
}

// Navigate to another view passing @Binding
NavigationLink(destination: DetailView(counter: $counter)) {
Text("Go to Detail View")
}
}
.padding()
}
}

// Detail view that displays counter value received through @Binding
struct DetailView: View {
// @Binding property wrapper to receive and bind to a value from another view
@Binding var counter: Int

var body: some View {
VStack {
Text("Detail View")
.font(.title)

Text("Counter: \(counter)")
.font(.headline)
}
.padding()
}
}

struct ContentView: View {
var body: some View {
NavigationView {
CounterView()
}
}
}

4. Layout:

  • Description: SwiftUI computes the layout of views based on their defined structure, alignment, and layout-related attributes. This ensures proper arrangement and presentation of views within containers.
  • Example: Defining layouts using HStack, VStack, ZStack, or custom layout modifiers to arrange and position views.
import SwiftUI

struct ZStackExample: View {
var body: some View {
ZStack {
// Blue background occupying the entire screen
Color.blue.edgesIgnoringSafeArea(.all)

VStack {
Text("Hello,")
.font(.largeTitle)
.foregroundColor(.white)

Text("ZStack!")
.font(.title)
.foregroundColor(.white)
}

// Red circle positioned at the center of the ZStack
Circle()
.foregroundColor(.red)
.frame(width: 150, height: 150)

// Green rectangle overlaid on top-left corner
Rectangle()
.foregroundColor(.green)
.frame(width: 100, height: 100)
.offset(x: -150, y: -300)
}
}
}

4. Deinitialization:

  • Description: This marks the end of a SwiftUI view’s lifecycle. It allows for cleanup or releasing resources before the view is removed from memory.
  • Example: Performing cleanup tasks, like invalidating timers or releasing resources, when the view is no longer needed.
import SwiftUI

struct ContentView: View {
var body: some View {
Text("Goodbye!")
}

// Deinitializer - executed when the view is deallocated
deinit {
print("ContentView is being deallocated.")
// Perform cleanup or deallocation here if necessary
}
}

// Example usage in a parent view or scene
struct ParentView: View {
@State private var showContent = true

var body: some View {
VStack {
if showContent {
ContentView()
} else {
Text("Another View")
}

Button("Toggle Content") {
self.showContent.toggle()
}
}
}
}

Understanding these lifecycle stages in SwiftUI is vital for developers to effectively manage view behavior, state changes, and resource utilization within their applications, leading to more responsive and efficient user interfaces.

Support my efforts by :

--

--

Shashidhar Jagatap

iOS Developer | Objective C | Swift | SwiftUI | UIKit | Combine | Crafting Engaging Mobile Experiences |