Skip to content

Instantly share code, notes, and snippets.

@levochkaa
Created January 25, 2024 15:24
Show Gist options
  • Save levochkaa/4f0b5faa0e66fd56f1c3867ba138fdaa to your computer and use it in GitHub Desktop.
Save levochkaa/4f0b5faa0e66fd56f1c3867ba138fdaa to your computer and use it in GitHub Desktop.
Examples of View redrawing in SwiftUI
@Observable
class VM {
var counter = 0
}
struct ContentView: View {
@State var vm = VM()
var body: some View {
// doesn't get executed on button tap
let _ = Self._printChanges()
VStack {
Button("Increase") { vm.counter += 1 }
OtherView()
}
.environment(vm)
}
}
struct OtherView: View {
@Environment(VM.self) var vm
var body: some View {
// doesn't get executed on button tap
let _ = Self._printChanges()
Text("Just view")
}
}
class VM: ObservableObject {
@Published var counter = 0
}
struct ContentView: View {
@StateObject var vm = VM()
var body: some View {
// executes every time, when button tapped
let _ = Self._printChanges()
VStack {
Button("Increase") { vm.counter += 1 }
OtherView()
}
.environmentObject(vm)
}
}
struct OtherView: View {
@EnvironmentObject var vm: VM
var body: some View {
// executes every time, when button tapped
let _ = Self._printChanges()
Text("Just view")
}
}
struct ContentView: View {
@State var counter = 0
var body: some View {
// doesn't get executed on button tap
let _ = Self._printChanges()
VStack {
Button("Increase") { counter += 1 }
OtherView(counter: $counter)
}
}
}
struct OtherView: View {
@Binding var counter: Int
var body: some View {
// doesn't get executed on button tap
let _ = Self._printChanges()
Text("Just view")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment