【问题标题】:Unable to use combine with TextField无法与 TextField 结合使用
【发布时间】:2021-02-05 17:30:16
【问题描述】:

我正在尝试使用 combine 将数据传递给 TextField。通过创建数据模型并使用 observableObject,但是当我在 textField 中使用它时,它会显示错误。 无法将“字符串”类型的值转换为预期的参数类型“绑定”。看不懂。

数据模型

struct People: Identifiable {
    var id = UUID()
    var name: String
    var amount: String
}

let peopleData = [
    People(name: "A",amount: ""),
    People(name: "B",amount: ""),
    People(name: "C",amount: "")
]

ObservableObject

import Combine
class PeopleAllData: ObservableObject{
    @Published var peopleStore: [People] = peopleData
}

文本字段

@ObservedObject var store = PeopleAllData()

                    List{

                        ForEach(store.peopleStore){ item in
                        HStack {
                            TextField("person Name", text: item.name) //Error:- Cannot convert value of type 'String' to expected argument type 'Binding<String>'

                            Button(action: {}) {
                                Image(systemName: "minus.circle")
                                    .foregroundColor(.red)
                            }
                        }
                            
                        }
                        
                        
                        
                    }
                    .frame(width: screen.width, height: screen.height)

【问题讨论】:

标签: swiftui


【解决方案1】:

您需要Binding 通过ObservedObject 来数组元素,如下所示

ForEach(store.peopleStore.indices, id: \.self){ i in
    HStack {
        TextField("person Name", text: $store.peopleStore[i].name)

【讨论】:

  • 能否请您解释一下我做错了什么以及为什么您的解决方案有效?
猜你喜欢
  • 1970-01-01
  • 2019-12-22
  • 2016-04-29
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多