In my SwiftUI app on macOS Sonoma I am using several Picker views. Here is one example:
Picker("Berichtsart", selection: $report.reportType) {
ForEach(ReportType.allCases) { option in
Image(systemName: option.iconString)
.help(option.description)
}
}
.fixedSize()
.pickerStyle(.segmented)
.labelsHidden()
.onChange(of: report.reportType) {
// Do something here when the user changes the selection thru the picker
reports.push(report)
}
The onChange closure get executed every time report.reportType changes. It runs when the user clicks on a different segment of the Picker, but it also runs if some other code changes the value of the Binding.
But I am looking for a way to run the code in the onChange only when the user triggers the change through the picker, and not, when some other code changes report.
TLDR: I want to run some code when a user actively changes the selection on a Picker, but not if something else changes the Binding the picker uses to store its selection.
Any hints and pointers are greatly appreciated. Thanks!
Picker("Berichtsart", selection: $myvar)and corresponding.onChange(of: myvar)where you update thereport.reportTypeas well as do your code just for Picker selection.reportas well, so I can updatemyvvarin casereportchanges. This update will then trigger the code that I want to run only on Picker selection.myvarchanges, I can updatereportwithout a problem. But how will bemyvarbe updated, in casereport.reportTypechanges through some other user interaction? The way I do it (which might be wrong) is to listen to changes toreport, and then updatemyvar, which then triggers the code I only want to run when the user uses the picker.