Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/115.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Can';t在TextField-'中创建绑定;找不到$social';范围内';_Ios_Swift_Swiftui - Fatal编程技术网

Ios Can';t在TextField-'中创建绑定;找不到$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.

我无法使用我的“username”属性创建绑定-Xcode给了我错误“无法在范围中找到$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)
}

工作起来很有魅力!非常感谢