【发布时间】:2021-07-03 02:22:11
【问题描述】:
我有一个简单的类来在我的 SwiftUI 应用中存储一些数据:
final class UserData: ObservableObject {
@Published var id = 1
@Published var name = "Name"
@Published var description = "Initial text"
}
我还在主应用结构中将其定义为EnvironmentObject:
ContentView(document: file.$document)
.environmentObject(UserData())
在我的内容视图中,我嵌入了一个 UIKit 文本视图:
EditorTextView(document: $document.text)
其中 EditorTextView 是通过UIViewRepresentable 应用的UITextView。
现在,我要做的是更新 EditorTextView 中的 UserData,例如,将一些用户输入存储到 UserData.description。所以我在我的 Coordinator 中定义了如下的类(代码只是举例):
class Coordinator: NSObject, UITextViewDelegate {
@ObservedObject var userData = UserData()
...
// Somewhere in the code, I update UserData when user taps Enter:
func textViewDidChange(_ textView: UITextView) {
if (textView.text.last == "\n") {
userData.description = "My New Text"
}
}
我的问题是:
虽然它使用“我的新文本”进行了更新(如调试器所示),但 userData.description 的值再次使用“初始文本”值重新启动。就像每次都创建 UserData 类一样。
我尝试使用@StateObject 代替@ObservedObject,但没有任何区别。
【问题讨论】:
-
你要下定决心,是环境物体还是观察物体?
-
它是环境对象(使其可用于所有视图),但我在 uikit 包装器中使用了
@ObservedObject,因为我不能在那里使用@EnvironmentObject
标签: ios swift swiftui uiviewrepresentable environmentobject