SwiftUI iOS15 绑定 ForEach 正在关闭 TextField KeyBoard
SwiftUI iOS15 Binding ForEach is dismissing TextField KeyBoard
正如 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()
}
}
有什么建议吗?
对不起大家,
我在阅读 post 时发现了这个问题。
ForEach 里面的 id 必须是 .id,否则它会刷新所有列表,因为标题正在改变
ForEach ($tasks, id:\.id) { $task in
TextField("Click", text: $task.title)
}
现在键盘不会关闭。
如果有人需要我就让post
你的结构是可识别的,所以它很简单:
ForEach ($tasks) { $task in
TextField("Click", text: $task.title)
}
正如 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()
}
}
有什么建议吗?
对不起大家, 我在阅读 post 时发现了这个问题。 ForEach 里面的 id 必须是 .id,否则它会刷新所有列表,因为标题正在改变
ForEach ($tasks, id:\.id) { $task in
TextField("Click", text: $task.title)
}
现在键盘不会关闭。
如果有人需要我就让post
你的结构是可识别的,所以它很简单:
ForEach ($tasks) { $task in
TextField("Click", text: $task.title)
}