在下面的示例中,如果我在TextField中键入文本,则该文本将被追加到列表中,并且该行将成为选择(如输入文本后单击按钮所示),但该行不会突出显示。如果在添加新项之前已经选择并突出显示了另一行,那么新一行将按预期突出显示。为什么新文本没有突出显示?
import SwiftUI
@main
struct SwiftUI_List_Bug_TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@StateObject private var fruitList = FruitList()
@State var newFruitName = ""
var body: some View {
List($fruitList.fList, id: .self, selection: $fruitList.selectedFruit) { $f in
Text(f)
}
TextField( "New fruit", text: $newFruitName, onCommit: addNewFruitName)
Button ("Print selected fruit name") {
print(fruitList.selectedFruit as Any)
}
}
func addNewFruitName () {
if newFruitName.count > 0 && !fruitList.fList.contains(newFruitName) {
fruitList.fList.append(newFruitName)
fruitList.selectedFruit = newFruitName //<-- This selects the row, as demonstrated when the button is clicked, but the selection does not highlight
}
}
}
class FruitList : ObservableObject {
@Published var fList : [String] = ["apple", "orange", "pear"]
@Published var selectedFruit : String?
}
对于SwiftUI来说,一个事件中的两个更新通常不工作,在这种情况下,通常的解决方法是将第二次更新延迟到下一个事件周期。
这里是一个修复。Xcode 13.4/macOS 12.4
fruitList.fList.append(newFruitName)
DispatchQueue.main.async { // << postpone !!
fruitList.selectedFruit = newFruitName // << here !!
}