我是SwiftUi的新手,但遇到一个我无法修复的错误。 基本上,我想在SettingsView中更改AB类的名称属性。
此外,我还有一些问题,希望任何人都能回答。
class User: ObservableObject {
@Published var name: String
...
@Publsihed var ab: [AB]
@Published var currentAb: AB?
internal init(name: String, ab: [AB]) {
self.name = name
self.ab = ab
self.currentAb = ab.first
}
}
class AB: ObervableObject {
@Published var name: String
...
}
由于TextField(“新名称”,文本:$ user.currentAb.wrappedValue.name),我在这里收到错误消息。
struct SettingsView: View {
@EnvironmentObject var user: User
var body: some View {
Form { //Error: Unable to infer complex closure return type; add explicit type to disambiguate
Section(header: Text("")) {
TextField("new name", text: $user.currentAb.wrappedValue.name) // <- Error is shown here
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
}
谢谢。
答案 0 :(得分:2)
最好将其分成不同的视图,例如
var body: some View {
Form {
Section(header: Text("")) {
if user.currentAb != nil {
SomeNameView(vm: user.currentAb!)
} else {
Text("any holder view here")
}
}
}
}
和单独的视图
struct SomeNameView: View {
@ObservedObject var vm: AB
var body: some View {
TextField("new name", text: $vm.name)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}