问题描述
我想通过 Struct
的 init()
方法在 SwiftUI 中初始化 @State
var 的值,所以它可以从准备好的字典中获取正确的文本,以便在 TextField 中进行操作.源代码如下所示:
I would like to initialise the value of a @State
var in SwiftUI through the init()
method of a Struct
, so it can take the proper text from a prepared dictionary for manipulation purposes in a TextField.The source code looks like this:
struct StateFromOutside: View {
let list = [
"a": "Letter A",
"b": "Letter B",
// ...
]
@State var fullText: String = ""
init(letter: String) {
self.fullText = list[letter]!
}
var body: some View {
TextField($fullText)
}
}
不幸的是,执行失败并出现错误 Thread 1: Fatal error: Accessing State外部 View.body
Unfortunately the execution fails with the error Thread 1: Fatal error: Accessing State<String> outside View.body
我该如何解决这种情况?预先非常感谢您!
How can I resolve the situation? Thank you very much in advance!
推荐答案
我会尝试在 onAppear
中初始化它.
I would try to initialise it in onAppear
.
struct StateFromOutside: View {
let list = [
"a": "Letter A",
"b": "Letter B",
// ...
]
@State var fullText: String = ""
var body: some View {
TextField($fullText)
.onAppear {
self.fullText = list[letter]!
}
}
}
或者,更好的是,使用模型对象(链接到您的视图的 BindableObject
)并在那里完成所有初始化和业务逻辑.您的视图将更新以自动反映更改.
Or, even better, use a model object (a BindableObject
linked to your view) and do all the initialisation and business logic there. Your view will update to reflect the changes automatically.
更新:BindableObject
现在更名为 ObservableObject
.
Update: BindableObject
is now called ObservableObject
.
这篇关于SwiftUI @State var 初始化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!