Ask Your Question
0

Can the entire View be prevented from being redrawn every second when only a single @State property is updated every second by a Timer in SwiftUI?

asked 2023-01-15 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-05-10 11:00:00 +0000

devzero gravatar image

Yes, it is possible to prevent the entire View from being redrawn every second when only a single @State property is updated every second by a Timer in SwiftUI.

This can be achieved by using the @ObservedObject property wrapper instead of the @State property wrapper.

@ObservedObject is used to wrap an instance of a class that conforms to the ObservableObject protocol, which allows us to update specific properties without redrawing the entire View.

Here's an example:

class MyViewModel: ObservableObject {
    @Published var currentTime = Date()

    init() {
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
            self.currentTime = Date()
        }
    }
}

struct ContentView: View {
    @ObservedObject var viewModel = MyViewModel()

    var body: some View {
        Text(viewModel.currentTime.description)
    }
}

In this example, the ViewModel class conforms to the ObservableObject protocol and contains a @Published property called currentTime.

The ContentView observes the viewModel using the @ObservedObject property wrapper, and only renders the Text view when the currentTime property changes.

By using @ObservedObject instead of @State, we ensure that only the Text view is redrawn when the currentTime property updates, instead of redrawing the entire View.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-15 11:00:00 +0000

Seen: 17 times

Last updated: May 10 '22