I use Table in my CoreData app for macOS
@FetchRequest(sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)]) private var categories: FetchedResults<Categories>
@State private var selectedCategoryID: Categories.ID?
and I'm wondering how I could catch change of selected row. If I try .onChange() as shown below then code can't be compiled due to error "Cannot call value of non-function type 'Categories.ID?' (aka 'Optional<Optional>')"
Table(categories, selection: $selectedCategoryID) {
TableColumn("Name", value \.name!)
TableColumn("Type", value: \.type!)
}.onChange(of: selectedCategoryID {
print("Selected row changed.")
}
Thank you.
CodePudding user response:
I finally found the root cause .onChange() must looks like
.onChange(of: selectedCategoryID) { selected in
print("Selected row is \(selected)")
}
CodePudding user response:
onChange
is "to trigger a side effect", e.g. something unrelated. If you want to update a related value, then a trick is to move it into a struct with some logic, e.g.
struct TableConfig {
var selectedCategoryID: CategoryID? {
didSet {
counter
}
}
var counter = 0
mutating func reset() {
selectedCategoryID = nil
counter = 0
}
}
...
@State var config = TableConfig()
...
Table(categories, selection: $config.selectedCategoryID)