Created
January 25, 2024 15:24
-
-
Save levochkaa/4f0b5faa0e66fd56f1c3867ba138fdaa to your computer and use it in GitHub Desktop.
Examples of View redrawing in SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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