简体   繁体   English

如何从外部更新 SwiftUI 视图状态(例如 UIViewController)

[英]How to update a SwiftUI view state from outside (UIViewController for example)

I have a SwiftUI view:我有一个 SwiftUI 视图:

struct CatView : View {

    @State var eyesOpened: Bool = false

    var body: some View {
       Image(uiImage: eyesOpened ? #imageLiteral(resourceName: "OpenedEyesCat") : #imageLiteral(resourceName: "ClosedEyesCat"))
    }
}

I'm trying to integrate it with in a regular UIViewController.我正在尝试将它与常规 UIViewController 集成。

let hostingVC = UIHostingController<CatView>(rootView: cat)
addChild(hostingVC)
view.addSubview(hostingVC.view)
hostingVC.view.pinToBounds(of: view)

Now in the UIViewController if I try to set the eyesOpened property I get a现在在 UIViewController 中,如果我尝试设置 eyeOpened 属性,我会得到一个

Thread 1: Fatal error: Accessing State<Bool> outside View.body

How are we supposed to make this work?我们应该如何进行这项工作? Are SwiftUI views not supposed to work in this scenario? SwiftUI 视图不应该在这种情况下工作吗?

@State is the wrong thing to use here. @State在这里使用是错误的。 You'll need to use @ObservedObject .您需要使用@ObservedObject

@State: Used for when changes occur locally to your SwiftUI view - ie you change eyesOpened from a toggle or a button etc from within the SwiftUI view it self. @State:用于当您的 SwiftUI 视图在本地发生更改时 - 即您在 SwiftUI 视图中通过切换或按钮等更改 eyeOpened。

@ObservedObject: Binds your SwiftUI view to an external data source - ie an incoming notification or a change in your database, something external to your SwiftUI view. @ObservedObject:将 SwiftUI 视图绑定到外部数据源 - 即传入通知或数据库中的更改,SwiftUI 视图外部的内容。

I would highly recommend you watch the following WWDC video - Data Flow Through SwiftUI我强烈建议您观看以下WWDC 视频 - 通过 SwiftUI 的数据流

There is something called the notification center that you could use.您可以使用称为通知中心的东西。 In short, it is a way that views can communicate between each other without actually modifying anything in each other.简而言之,这是一种视图之间可以相互通信的方式,而无需实际修改彼此的任何内容。

How it works is view A sends a notification to a central hub from which view B hears said notification.它的工作原理是视图 A 向中央集线器发送通知,视图 B 从中听到所述通知。 When view B hears the notification it activates, and calls a function defined by the user.当视图 B 听到它激活的通知时,并调用用户定义的函数。

For a more detailed explanation, you can refer to: https://learnappmaking.com/notification-center-how-to-swift/更详细的解释可以参考: https : //learnappmaking.com/notification-center-how-to-swift/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM