Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Created February 25, 2024 15:54
Show Gist options
  • Save hmlongco/00c290b03e50af00b6e65001d06c9793 to your computer and use it in GitHub Desktop.
Save hmlongco/00c290b03e50af00b6e65001d06c9793 to your computer and use it in GitHub Desktop.
Clearing StateObject with ID
struct ChildStateDemo: View {
@State var account = 1
var body: some View {
VStack(spacing: 20) {
SubView(id: account)
.id(account) // required to change subview state
Button("Account 1") {
account = 1
}
Button("Account 2") {
account = 2
}
Button("Account 3") {
account = 3
}
}
}
}
struct SubView: View {
@StateObject var vm: SubViewModel
init(id: Int) {
self._vm = .init(wrappedValue: .init(id: id))
}
var body: some View {
Text("Selected account is \(vm.id)")
}
}
class SubViewModel: ObservableObject {
let id: Int
init(id: Int) {
self.id = id
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment