【发布时间】:2019-12-16 22:57:24
【问题描述】:
我想在每次“重新分配”@ObservedObject 时重置一些 @State。如何实现?
class Selection: ObservableObject {
let id = UUID()
}
struct ContentView: View {
@State var selectedIndex: Int = 0
var selections: [Selection] = [Selection(), Selection(), Selection()]
var body: some View {
VStack {
// Assume the user can select something so selectedIndex changes all the time
// SwiftUI will just keep updating the same presentation layer with new data
Button("Next") {
self.selectedIndex += 1
if self.selectedIndex >= self.selections.count {
self.selectedIndex = 0
}
}
SelectionDisplayer(selection: self.selections[self.selectedIndex])
}
}
}
struct SelectionDisplayer: View {
@ObservedObject var selection: Selection {
didSet { // Wish there were something *like* this
print("will never happen")
self.tabIndex = 0
}
}
@State var tapCount: Int = 0 // Reset this to 0 when `selection` changes from one object to another
var body: some View {
Text(self.selection.id.description)
.onReceive(self.selection.objectWillChange) {
print("will never happen")
}
Button("Tap Count: \(self.tapCount)") {
self.tapCount += 1
}
}
}
我知道onReceive,但我不想修改状态以响应objectWillChange,而是在对象本身被切换时。在具有引用类型的 UIKit 中,我会使用 didSet 但这在这里不起作用。
我确实尝试过为此使用PreferenceKey (gist),但这似乎太过分了。
【问题讨论】:
-
我很难理解你的目标。你能把
Selection的代码贴出来吗? -
but I'm not looking to modify state in response to objectWillChange but rather when the object itself is switched out是一样的还是我遗漏了什么? -
@Lu_No 不一样。我已经更新了我的代码以明确这一点。
-
@kontiki 这只是一个占位符。可以是任何东西。