如何解决更新 TextField 中的值并相应地更新其数组索引
我无法更新通过 for 每个循环显示的数组中的值。这些值显示在文本字段中。
有问题的代码
struct EditItemView: View {
@State var recipestep: [String]
@State var stepInfo: String = ""
@State var textFieldCount: Int = 1
@State var stepNumber: [Int]
@State var recordsCount = 2
var body: some View {
//a bunch of code between here and the list,does not apply
vstack {
List {
ForEach(0..<recipestep.count,id: \.self) { index in
HStack {
Text(String(stepNumber[index]) + ".").bold()
EditorViewEdit(container: self.$recipestep,index: index,text: recipestep[index])
}
}.onDelete { (indexSet) in
stepNumber.remove(atOffsets: indexSet)
recipestep.remove(atOffsets: indexSet)
}
ForEach 循环中的以下代码段是我用来使列表中的每个文本字段可编辑的代码(因为我不知道有任何其他方法可以使文本字段在列表中工作):
EditorViewEdit(container: self.$recipestep,text: recipestep[index])
上面代码中引用的结构体如下:
struct EditorViewEdit : View {
var container: Binding<[String]>
var index: Int
@State var text: String
var body: some View {
TextField("",text: self.$text,onCommit: {
self.container.wrappedValue[self.index] = self.text
})
}
}
问题
如何更改 foreach 循环中的文本字段并相应地更新其在 @State var recipestep: [String]
中的值?例如,我在 for each 循环中编辑第一个 TextField - 如何使用新值更新数组中的索引 0?
解决方法
有很多方法可以在 foreach 循环中更改文本字段 并在recipeStep中有它的价值。尝试这样的事情:
import SwiftUI
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State var recipeStep = ["recipe step 1","recipe step 2","recipe step 3"]
var body: some View {
VStack {
EditItemView(recipeStep: $recipeStep)
Text(recipeStep.description)
}
}
}
struct EditItemView: View {
@Binding var recipeStep: [String]
var body: some View {
VStack {
List {
ForEach(recipeStep.indices,id: \.self) { index in
HStack {
Text(String(index) + ".").bold().foregroundColor(.red)
TextField("Recipe step",text: $recipeStep[index])
}
}.onDelete { indexSet in
recipeStep.remove(atOffsets: indexSet)
}
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。