【发布时间】:2022-01-07 12:51:35
【问题描述】:
正如 WWDC21“SwiftUI 中的新功能”中所建议的,现在可以在 ForEach 中管理绑定,但是我的 TextField 有问题,如果我添加一个字符,KeyBoard 就会消失。
struct TESTVIEW: View {
public struct MyTask: Identifiable, Codable, Hashable {
public var id: UUID = UUID()
var title: String = ""
}
@State var tasks: [MyTask] = []
var body: some View {
VStack {
Text("NEW")
List {
ForEach ($tasks, id:\.self) { $task in
TextField("Click", text: $task.title)
}
.onDelete(perform: delete)
Button(action: {
tasks.append(MyTask())
}) {
Label("New task", systemImage: "plus.circle.fill")
}
.padding()
.accentColor(.white)
}
Text("OLD")
List {
ForEach (tasks.indices, id:\.self) { idx in
let bindingTask = Binding(get: {tasks[idx]},set: {value in tasks[idx] = value})
TextField("Click", text: bindingTask.title)
}
.onDelete(perform: delete)
Button(action: {
tasks.append(MyTask())
}) {
Label("New task", systemImage: "plus.circle.fill")
}
.padding()
.accentColor(.white)
}
}
.preferredColorScheme(.dark)
}
func delete(at offsets: IndexSet) {
tasks.remove(atOffsets: offsets)
}
}
struct TESTVIEW_Previews: PreviewProvider {
static var previews: some View {
TESTVIEW()
}
}
有什么建议吗?
【问题讨论】:
标签: swift iphone swiftui ios15