[英]State not updating to another view in swiftUI
I am using this for saving user info in user defaults for user isRegsitered.我正在使用它来将用户信息保存在用户 isRegsitered 的用户默认值中。
struct UserKeys {
static let isUserRegistered = "isUserRegistered"
}
@propertyWrapper
struct UserDefault<T> {
let key: String
let defaultValue: T
init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
}
set {
UserDefaults.standard.set(newValue, forKey: key)
}
}
}
final class UserSettings: ObservableObject {
let objectWillChange = PassthroughSubject<Void, Never>()
@UserDefault(UserKeys.isUserRegistered, defaultValue: false)
var isUserRegistered: Bool {
willSet {
objectWillChange.send()
}
}
}
// The Popup Login window on Same Dashboard View. // 同一仪表板视图上的弹出登录 window。
struct PopUpWindow: View {
@ObservedObject var userRepo = UserSettings()
Button(action: {
// Dismiss the PopUp
withAnimation(.linear(duration: 0.3)) {
userRepo.isUserRegistered = true
show = false
hideKeyboard()
}
}, label: {
Text("Submit")
& further I am listing in DashBoardView View as - & 此外,我在 DashBoardView 视图中列出 -
struct DashBoardView: View {
@ObservedObject var userRepo = UserSettings()
private var content: some View {
if !userRepo.isUserRegistered {
return PopUpWindow(show: .constant(true)) .eraseToAnyView()
}
// .. Other conditions ..
So basically I have popup with Login box so after submit I am trying to dismiss dialog & want to listen value userRepo.isUserRegistered
所以基本上我弹出了登录框,所以在提交后我试图关闭对话框并想听值
userRepo.isUserRegistered
By initializing UserSettings
class independently in both PopUpWindow
and DashBoardView
, you are actually saying that each view is managing its own data, hence the two views are not sharing the same data.通过在
PopUpWindow
和DashBoardView
中独立初始化UserSettings
class ,您实际上是在说每个视图都在管理自己的数据,因此两个视图不共享相同的数据。
You should not initialize your UserSettings
class from the PopUpWindow
view, but instead, pass an instance to from DashBoardView
.您不应该从
PopUpWindow
视图初始化您的UserSettings
class ,而是从DashBoardView
传递一个实例。 The code would look like this:代码如下所示:
PopUpWindow弹出窗口
struct PopUpWindow: View {
@ObservedObject var userRepo: UserSettings
Button(action: {
// Dismiss the PopUp
withAnimation(.linear(duration: 0.3)) {
userRepo.isUserRegistered = true
show = false
hideKeyboard()
}
}, label: {
Text("Submit")
// .. Other conditions ..
and then:接着:
DashBoardView仪表板视图
struct DashBoardView: View {
@ObservedObject var userRepo = UserSettings()
private var content: some View {
if !userRepo.isUserRegistered {
return PopUpWindow(userRepo: userRepo, show: .constant(true)) .eraseToAnyView()
}
// .. Other conditions ..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.