Ios Can';t在TextField-'中创建绑定;找不到$social';范围内';
我无法使用我的“username”属性创建绑定-Xcode给了我错误“无法在范围中找到$social”。以下是一些基本代码: 我有问题的观点:Ios Can';t在TextField-'中创建绑定;找不到$social';范围内';,ios,swift,swiftui,Ios,Swift,Swiftui,我无法使用我的“username”属性创建绑定-Xcode给了我错误“无法在范围中找到$social”。以下是一些基本代码: 我有问题的观点: struct ProfileSetter: View { @Binding var profile: Profile var body: some View { ForEach(profile.socials, id: \.id) { social in TextField(social.
struct ProfileSetter: View {
@Binding var profile: Profile
var body: some View {
ForEach(profile.socials, id: \.id) { social in
TextField(social.medium.rawValue, text: $social.username) //-> cannot find $social in scope
}
}
}
其母公司:
struct ProfileView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
ProfileSetter(profile: $viewModel.myProfile)
}
}
简化视图模型:
class ViewModel: ObservableObject {
@Published var myProfile = Profile(socials: [//multiple instances of Social])
}
最后,模型:
struct Profile {
// other properties
var socials: [Social]
}
struct Social {
// other properties
var username: String
}
将文本字段替换为
文本(social.username)
效果很好,因此创建绑定似乎是个问题。您不能直接绑定到值,应该通过父对象进行绑定,如
ForEach(profile.socials.indices, id: \.self) { index in
TextField(profile.socials[index].medium.rawValue,
text: $profile.socials[index].username)
}
工作起来很有魅力!非常感谢