In the example below, if I type text into the TextField, the text is appended to the list and that row becomes the selection (as demonstrated by clicking on the button after entering the text), but the row is not highlighted. If another row is already selected and highlighted before adding the new item, then the new one highlights as expected. Why is the new text not highlighted?
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?
}
CodePudding user response:
Very often two updates in one event does not work for SwiftUI, a usual workaround in such cases is to delay second update to next event cycle.
Here is a fix. Tested with Xcode 13.4 / macOS 12.4
fruitList.fList.append(newFruitName)
DispatchQueue.main.async { // << postpone !!
fruitList.selectedFruit = newFruitName // << here !!
}