ios - 无法在 TextField 中创建绑定(bind) - 范围内的 'cannot find $social''

标签 ios swift swiftui

我无法使用我的“用户名”属性创建绑定(bind) - 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)
    }
}

简化的 View 模型:

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
}

将文本字段替换为 Text(social.username) 效果很好,因此创建绑定(bind)似乎是问题所在。

最佳答案

你不能直接绑定(bind)到值,你应该通过父对象来绑定(bind),比如

ForEach(profile.socials.indices, id: \.self) { index in
    TextField(profile.socials[index].medium.rawValue, 
        text: $profile.socials[index].username)
}

关于ios - 无法在 TextField 中创建绑定(bind) - 范围内的 'cannot find $social'',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65186044/

相关文章:

swift - 如何在 SwiftUI 中的列表下方添加按钮?

ios - 打字机效果文字动画

ios - 根据选择的选项卡更改 Tabview 颜色-Swiftui

ios - 如何在 Xcode 9 中使用带有 playground 的自定义框架

ios - Html 字符串转换为属性字符串\U00002028\n ios

ios - PhotoKit - Swift 4 - 如何查找相同的照片或重复的照片 - PHFetchResult<PHAsset>

ios - Swift 3 面向协议(protocol)编程导致随机 SIGBUS 崩溃

swift - Swift 在任何情况下如何处理 sin 和 cos?

swift - 在 JPEG 图像上绘制一条简单的线

ios - 在添加和删除第二个按钮时,在SwiftUI中保持导航项按钮对齐