提问者:小点点

iOS Swiftui应用程序返回前景重置观察对象


我有一个应用程序,它使用ObservedObject在不同视图之间共享数据。

定义viewmodel

class MyViewModel: ObservableObject {
    @Published var language: String?
}

现在用于ContentView

struct ContentView: View {
    @ObservedObject private var myViewModel = MyViewModel()

    var body: some View {
        Home()
        .environmentObject(self.myViewModel)
    }
}

这里是家()

struct Home: View {
    @EnvironmentObject var myViewModel: MyViewModel

    var body: some View {
        VStack {
            Text(self.myViewModel.language ?? "")
                .onReceive(self.myViewModel.$language, perform: { language in
                    print(language)
                })
            Button(action: {
                self.myViewModel.language = "American English"
            }, label: {
                Text("Set the language")
            })
        }
    }
}

此处的onreceive用于调试目的

单击该按钮会将语言设置为“American English”,Text()将显示更新后的字符串。

现在将应用程序放在后台,然后单击图标将其调回前台:尽管UI上没有任何改变,myviewmodel是零。

为了“恢复”状态,我修改了ContentView以接收“前台通知”,如https://www.hackingwithswift.com/books/ios-swiftui/how-to-be-notifed-when-your-swiftui-app-moves-to-the-backround所建议的

struct ContentView: View {
    @ObservedObject private var myViewModel = MyViewModel()

    var body: some View {
        Home()
        .environmentObject(self.myViewModel)
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
           self.myViewModel.language = "American English"
        }
    }
}

Home()的onReceive中的调试打印可以工作并显示正确的字符串,但text()中的调试打印会消失,就好像它接收到的值为nil,随后没有刷新。

知道吗?


共1个答案

匿名用户

改用stateobject

struct ContentView: View {
    @StateObject private var myViewModel = MyViewModel()

...