gpt4 book ai didi

ios - 在 SwiftUI 中更新其他变量时如何修改/重置@State

转载 作者:行者123 更新时间:2023-12-01 18:36:20 26 4
gpt4 key购买 nike

我想重置一些@State每次@ObservedObject被“重新分配”。如何实现?


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 ),但它似乎太过分了。

最佳答案

目前(Beta 5),最好的方法可能是使用构造函数加上泛型 ObservableObject对于我想在数据更改时重置的项目。这允许一些 @State被保留,而一些被重置。

在下面的示例中,tapCount每次重置 selection更改,而 allTimeTaps不是。

class StateHolder<Value>: ObservableObject {
@Published var value: Value
init(value: Value) {
self.value = value
}
}

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 though
Button("Next") {
self.selectedIndex += 1
if self.selectedIndex >= self.selections.count {
self.selectedIndex = 0
}
}
SelectionDisplayer(selection: self.selections[self.selectedIndex])
}
}
}

struct SelectionDisplayer: View {

struct SelectionState {
var tapCount: Int = 0
}

@ObservedObject var selection: Selection
@ObservedObject var stateHolder: StateHolder<SelectionState>
@State var allTimeTaps: Int = 0

init(selection: Selection) {
let state = SelectionState()
self.stateHolder = StateHolder(value: state)
self.selection = selection
}

var body: some View {
VStack {
Text(self.selection.id.description)
Text("All Time Taps: \(self.allTimeTaps)")
Text("Tap Count: \(self.stateHolder.value.tapCount)")
Button("Tap") {
self.stateHolder.value.tapCount += 1
self.allTimeTaps += 1
}
}
}
}

在寻找解决方案时,我很感兴趣地发现您无法初始化 @State init 中的变量.编译器会提示在访问 self 之前还没有设置所有属性。

关于ios - 在 SwiftUI 中更新其他变量时如何修改/重置@State,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57426007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com