Development record of developer who study hard everyday.

, ,

When SwiftUI rerenders the view

 When SwiftUI rerenders the view

iOS development blog

SwiftUI rerenders views when their associated state or observed object changes.


1. Changes to @StateObject or @ObservedObject Properties

- When a property marked with @StateObject (or @ObservedObject) emits a change, SwiftUI reevaluates the views that depend on those properties.


2. Parent View Changes

- If a parent view that includes ContentView in its body is re-rendered, SwiftUI may recreate the ContentView.

- This happens because SwiftUI's rendering system works hierarchically.


3. Environment Changes.

If an @Environment property in ContentView or any parent view changes, it can trigger the recreation of the view.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import SwiftUI
import Combine
 
class MyViewModel: ObservableObject {
    @Published var username: String = ""
    @Published var isLoggedIn: Bool = false
 
    private var cancellables = Set<AnyCancellable>()
 
    init() {
        // Observing changes to `username`
        $username
            .sink { newValue in
                print("Username changed to: \(newValue)")
            }
            .store(in&cancellables)
    }
 
    func login() {
        // Simulating a login process
        isLoggedIn = true
    }
}
 
struct ContentView: View {
    @StateObject private var viewModel = MyViewModel()
 
    var body: some View {
        VStack {
            TextField("Enter username", text: $viewModel.username)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
 
            Button("Login") {
                viewModel.login()
            }
 
            if viewModel.isLoggedIn {
                Text("Welcome, \(viewModel.username)!")
            }
        }
        .padding()
    }
}
cs

Above code is example of Swift code with Combine framework.

On above example, SwiftUI rerenders view when @Published properties change.

(username or isLoggedIn)


So, It is important to minimize re-rendering view.

Here is the best practives to avoid unnecessary recreation.


1. Use @StateObject for ViewModel

- @StateObject ensures that the view model is created once per view lifecycle, even if the view is recreated.


2. Minimize Dependencies

- Avoid overly complex dependencies in the view hierarchy to limit unnecessary recomputation.


3. Extract Subviews

- Break the view into smaller subviews to isolate parts that change independently











Share:
Location: 미국 뉴욕

댓글 없음:

댓글 쓰기