![](/img/trans.png)
[英]View refreshing not triggered when ObservableObject is inherited in SwiftUI
[英]SwiftUI: Update views when conditions / ObservableObject changed while view is opened
我想这很可能是一个愚蠢的问题,但目前我正在努力。 为了避免大量代码,我简化了代码(见下文),但它应该显示问题。
我有多个不属于父母关系的观点。 在一个视图 (ViewA) 上,我设置了一个目标日期。 在另一个视图 (ViewB) 上,我根据目标日期是否在未来显示文本。 对于这两个视图,我都使用 ObservableObject。 我希望 ViewB 在打开时更改文本并且达到目标日期。 由于我使用标签@Published,我期待它直接工作。 但不幸的是,什么也没有发生。
这是我最初的方法。
我测试了更多解决方案,例如
但我想我的方法非常糟糕,我会有更好的解决方案。
非常感谢您的帮助。
谢谢,塞巴斯蒂安
搜索数据:
class SearchData: ObservableObject {
@Published var targetDate: Date = UserDefaults.standard.object(forKey: "targetDate") as? Date ?? Date() {
didSet {
UserDefaults.standard.set(self.targetDate, forKey: "targetDate")
}
}
}
观点一:
struct ViewA: View {
@ObservedObject var searchData = SearchData()
func setDate() {
searchData.targetDate = Date() + 120
}
var body: some View {
Button(action: {
self.setDate()
}) {
Text("Set Date")
}
}
}
视图 B:
struct ViewB: View {
@ObservedObject var searchData = SearchData()
var body: some View {
VStack() {
if searchData.targetDate > Date() {
Text("Text A")
} else {
Text("Text B")
}
Spacer()
Text("\(searchData.targetDate)")
}
.padding()
}
}
ViewA
和ViewB
使用不同的SearchData
实例。 如您所写,要直接发布作品,两个视图都必须使用一个可观察的 object 实例。
struct ViewA: View {
@ObservedObject var searchData: SearchData
/// ... other code
struct ViewB: View {
@ObservedObject var searchData: SearchData
/// ... other code
在你装箱的地方
let searchData = SearchData()
...
ViewA(searchData: searchData)
...
ViewB(searchData: searchData)
如果ViewA
和ViewB
存在于不同的视图层次结构中,那么可能更适合使用@EnvironmentObject
struct ViewA: View {
@EnvironmentObject var searchData: SearchData
/// ... other code
struct ViewB: View {
@EnvironmentObject var searchData: SearchData
/// ... other code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.