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.
Asked: 2023-01-15 11:00:00 +0000
Seen: 17 times
Last updated: May 10 '22