Created
February 25, 2024 15:54
-
-
Save hmlongco/00c290b03e50af00b6e65001d06c9793 to your computer and use it in GitHub Desktop.
Clearing StateObject with ID
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 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