大家好,我正在尝试在ForEach
中使用TextField
我在textField
的文本parameter
中输入binding
字符串时遇到问题
我有一个Manager
类,其中有2个字符串,它们应该是ForEach中的textField binding
class Manager: ObservableObject {
@Published var name: String = ""
@Published var address: String = ""
@Published var city: String = ""
}
现在,正如你在struct Test: View
中看到的,我对数组执行ForEach并返回3 TextFields,但我不知道如何在ForEach的TextField中关联@Published var name
、@Published var address
、@Published var city
。
struct Test: View {
var body: some View {
VStack {
ForEach(Info.infos.indices, id:\.self) { index in
TextField("\(Info.infos[index].title)", text: ???? )
}
}
}
}
有谁能告诉我实现这一目标的正确方法吗?
编辑
struct Info: Identifiable {
var scalableTitle: String
var description: String
var icon: String
let id = UUID()
}
extension Info {
static let rows: [Info] = [
Info(scalableTitle: "Text", description: "@Nome", icon: "doc.plaintext.fill"),
Info(scalableTitle: "Text", description: "@Pro", icon: "graduationcap.fill"),
Info(scalableTitle: "Text", description: "@Text", icon: "door.sliding.left.hand.open")
]
static let preview =
Info(scalableTitle: "Text", description: "@Test", icon: "doc.plaintext.fill") }
struct InfoRow: View {
@Binding var textFieldText: String
var info: Info
private var isEmpty: Bool { textFieldText.isEmpty }
private var activeColor: Color { isEmpty ? .orange : .accentColor}
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(info.scalableTitle)
.font(.comfortaa(.bold, size: .body))
.scaleEffect(isEmpty ? 1 : 0.9, anchor: .leading)
.foregroundColor(activeColor)
TextField(info.description, text: $textFieldText)
.font(.comfortaa(isEmpty ? .regular : .bold, size: .body))
.padding(8)
}
.animation(.default, value: isEmpty)
Image(systemName: info.icon)
.foregroundColor(isEmpty ? .orange : .accentColor)
.font(.title2)
}
.padding(16)
.overlay {
RoundedRectangle(cornerRadius: 10)
.stroke()
.foregroundColor(.accentColor)
}
.foregroundColor(.accentColor)
}
}
struct InfoView: View {
var info: [Info] = Info.rows
var body: some View {
VStack {
ForEach(info) { value in
InfoRow(textFieldText: <#T##Binding<String>#>, info: <#T##RowInfo#>)
}
}
}
}
1条答案
按热度按时间ycggw6v21#
ForEach是一个视图,而不是一个循环。如果你读了文档,它解释了可识别的数据。通常只有一个对象存储模型结构体的数组,例如: