正如 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()
}
}
有什么建議嗎?
uj5u.com熱心網友回復:
您的結構是可識別的,因此很簡單:
ForEach ($tasks) { $task in
TextField("Click", text: $task.title)
}
uj5u.com熱心網友回復:
對不起大家,我在閱讀我的帖子時發現了這個問題。ForEach 中的 id 必須是 .id,否則它將重繪 所有串列,因為標題正在更改
ForEach ($tasks, id:\.id) { $task in
TextField("Click", text: $task.title)
}
現在鍵盤不會關閉。
如果有人需要,我讓帖子
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/405329.html
標籤:
