The error can not discover '$settingsViewModel' in scope
is as a result of Picker
requires a binding for its choice parameter. Once you use a var settingsViewModel : SettingsViewModel = .init()
, you do not get a binding to your mannequin.
Whereas @State
does get you a binding, it ought to solely be used if it is thought of to be the proprietor of the thing. In any other case, if the proprietor is a mum or dad view, you may settle for it as a Binding
in your baby view or when utilizing @Observable
, you may settle for it as an object and get a binding to it in your baby view, utilizing @Bindable
.
Notice: Since your code wasn’t reproducible because of missing the DataHandler
class and the ColorOptionEnum
, I commented it out within the instance code beneath and added a pattern enum to make it work:
import Basis
import SwiftUI
enum ColorOptionEnum {
case inexperienced, blue, orange // <- circumstances must be lowercased
var shade: Shade {
change self {
case .inexperienced: return .inexperienced
case .blue: return .blue
case .orange: return .orange
}
}
}
@Observable
class DemoSettings {
var currentSelection : ColorOptionEnum = .inexperienced
// var dataHandler : DataHandler
// init() {
// let localdataHandler: DataHandler = .init()
// currentSelection = localdataHandler.currentBibleVersion
// dataHandler = localdataHandler
// }
}
//Guardian view
struct DemoSettingsRootView: View {
//State worth
@State personal var demoSettings = DemoSettings() // <- Guardian view owns the settings object
//Physique
var physique: some View {
DemoSettingsView(settings: demoSettings) // <- Settings handed to baby view as an (observable) object
}
}
//Little one view
struct DemoSettingsView: View {
//Parameters
var settings : DemoSettings // <- settings accepted from mum or dad as an object
//Physique
var physique: some View {
@Bindable var settings = settings // <- Right here, get a binding to the observable settings object
Textual content("Chosen mode: (String(describing: settings.currentSelection).capitalized)")
.foregroundStyle(settings.currentSelection.shade)
Type {
Picker("Mode", choice: $settings.currentSelection) { // <- use the binding for the choice parameter
Textual content("Inexperienced")
.tag(ColorOptionEnum.inexperienced)
Textual content("Blue")
.tag(ColorOptionEnum.blue)
}
}
}
}
#Preview {
DemoSettingsRootView()
}