[英]SwiftUI: Update views when conditions / ObservableObject changed while view is opened
I guess it is mostlikely a stupid question, but currently I am struggling.我想这很可能是一个愚蠢的问题,但目前我正在努力。 To avoid tons of code, I simplified the code (see below) but it should show the problem.
为了避免大量代码,我简化了代码(见下文),但它应该显示问题。
I've got multiple views that are not in a parental relationship.我有多个不属于父母关系的观点。 On one view (ViewA) I set a target date.
在一个视图 (ViewA) 上,我设置了一个目标日期。 On another view (ViewB) I show text, depending on the fact whether the target date is in future or not.
在另一个视图 (ViewB) 上,我根据目标日期是否在未来显示文本。 For both views I am using a ObservableObject.
对于这两个视图,我都使用 ObservableObject。 I would like to have that ViewB changes the text when it is open and the target date is reached at that time.
我希望 ViewB 在打开时更改文本并且达到目标日期。 Since I am using the tag @Published, I was expecting it works directly.
由于我使用标签@Published,我期待它直接工作。 But unfortunately, nothing happens.
但不幸的是,什么也没有发生。
This is my initial approach.这是我最初的方法。
I tested some more solutions, eg我测试了更多解决方案,例如
But I guess my approach(es) is (are) very bad I there will be a way better solution.但我想我的方法非常糟糕,我会有更好的解决方案。
Your help is really appreciated.非常感谢您的帮助。
Thanks, Sebastian谢谢,塞巴斯蒂安
SearchData:搜索数据:
class SearchData: ObservableObject {
@Published var targetDate: Date = UserDefaults.standard.object(forKey: "targetDate") as? Date ?? Date() {
didSet {
UserDefaults.standard.set(self.targetDate, forKey: "targetDate")
}
}
}
View A:观点一:
struct ViewA: View {
@ObservedObject var searchData = SearchData()
func setDate() {
searchData.targetDate = Date() + 120
}
var body: some View {
Button(action: {
self.setDate()
}) {
Text("Set Date")
}
}
}
View B:视图 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()
}
}
The ViewA
and ViewB
use different instances of SearchData
. ViewA
和ViewB
使用不同的SearchData
实例。 To make published work directly, as you wrote, both views have to use one instance of observable object.如您所写,要直接发布作品,两个视图都必须使用一个可观察的 object 实例。
struct ViewA: View {
@ObservedObject var searchData: SearchData
/// ... other code
struct ViewB: View {
@ObservedObject var searchData: SearchData
/// ... other code
and somewhere you crate them在你装箱的地方
let searchData = SearchData()
...
ViewA(searchData: searchData)
...
ViewB(searchData: searchData)
If ViewA
and ViewB
live in different view hierarchies then probably would be more appropriate to use @EnvironmentObject
如果
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.