【问题标题】:SwiftUI iOS15 Binding ForEach is dismissing TextField KeyBoardSwiftUI iOS15 Binding ForEach 正在关闭 TextField KeyBoard
【发布时间】: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


    【解决方案1】:

    你的结构是可识别的,所以很简单:

    ForEach ($tasks) { $task in
          TextField("Click", text: $task.title)
    }
    

    【讨论】:

      【解决方案2】:

      对不起, 我在阅读我的帖子时发现了这个问题。 ForEach 中的 id 必须是 .id,否则它会刷新所有列表,因为标题正在更改

      ForEach ($tasks, id:\.id) { $task in
            TextField("Click", text: $task.title)
      }
      

      现在键盘不会关闭。

      如果有人需要,我会发帖

      【讨论】:

        猜你喜欢
        • 2019-12-11
        • 2020-06-20
        • 2020-05-17
        • 1970-01-01
        • 2020-04-17
        • 1970-01-01
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多