Hello there,
I have a List that display all data from Realm database (Item object) and now want to set selection item for that list. My use case is that when newly Item created, the List should move selection to that new Item. I tried as below but still doesn’t work. I also tried to call selectedItem = newItem in main thread but still not work. I would greatly appreciate any assistance. Thank you!
import RealmSwift
class Item: Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var id: ObjectId
@Persisted var name = ""
}
struct ContentView: View {
@ObservedResults(Item.self) var items
@State private var selectedItem: Item? = nil
var body: some View {
VStack {
List(items, id: \.self, selection: $selectedItem) { item in
Text(item.name)
}
Button("Add Item") {
let newItem = Item()
newItem.name = "New Item"
do {
let realm = try Realm()
try realm.write {
realm.add(newItem)
}
selectedItem = newItem
// DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// selectedItem = newItem
// }
// DispatchQueue.main.async {
// selectedItem = newItem
// }
} catch {
print("Error adding item to Realm database: \(error.localizedDescription)")
}
}
}
}
}