![](/img/trans.png)
[英]Adjust View up with Keyboard show in SwiftUI 3.0 iOS15
[英]SwiftUI iOS15 Binding ForEach is dismissing TextField KeyBoard
正如 WWDC21“SwiftUI 中的新功能”中所建议的那样,现在可以在 ForEach 中管理绑定,但是我的 TextField 有问题,如果我添加一个字符,键盘就会被解散。
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()
}
}
有什么建议吗?
对不起大家,我在阅读我的帖子时发现了这个问题。 ForEach 中的 id 必须是.id,否则它将刷新所有列表,因为标题正在更改
ForEach ($tasks, id:\.id) { $task in
TextField("Click", text: $task.title)
}
现在键盘不会关闭。
如果有人需要,我让帖子
您的结构是可识别的,因此很简单:
ForEach ($tasks) { $task in
TextField("Click", text: $task.title)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.