gpt4 book ai didi

swift - 在Swift中didSet用于@Binding var

转载 作者:行者123 更新时间:2023-12-04 15:29:05 26 4
gpt4 key购买 nike

通常,我们可以快速使用didSet来监视变量的更新。但这不适用于@Binding变量。例如,我有以下代码:

@Binding var text {
didSet {
......
}
}

但是 didSet从未被调用过,知道吗?谢谢。

最佳答案

您不需要在didSet上使用@Binding观察器。

如果您想要didSet,因为您想计算text更改时显示的其他内容,则只需对其进行计算。例如,如果要显示text中的字符数:

struct ContentView: View {
@Binding var text: String

var count: Int { text.count }

var body: some View {
VStack {
Text(text)
Text(“count: \(count)”)
}
}
}

如果由于要对数据模型进行其他更改而想要观察 text,则从 View观察更改是错误的。您应该从模型的其他地方或 Controller 对象中观察更改,而不是从 View中观察。请记住,您的 View类型,而不是引用类型。 SwiftUI会在需要时创建它,并可能存储它的多个副本,或者根本不存储任何副本。

关于swift - 在Swift中didSet用于@Binding var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57953112/

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