Skip to content

Instantly share code, notes, and snippets.

@jaclync
Created October 31, 2023 07:41
Show Gist options
  • Save jaclync/c97ab04916ee72c09f60d01bc0ca2c03 to your computer and use it in GitHub Desktop.
Save jaclync/c97ab04916ee72c09f60d01bc0ca2c03 to your computer and use it in GitHub Desktop.
Binding a SwiftUI Picker selection to an ObservedObject's @published var
import SwiftUI
class MyData: ObservableObject {
// TIL: the type cannot be optional.
// If the selection type is optional, then the option in the UI & property here won't be binded.
@Published var selectedOption: String = "Option 2"
}
struct PickerSelectionTestView: View {
@ObservedObject var data = MyData()
let options = ["Option 1", "Option 2", "Option 3"]
var body: some View {
VStack {
Picker("Select an option", selection: $data.selectedOption) {
ForEach(options, id: \.self) {
Text($0)
}
}
}
}
}
#Preview {
PickerSelectionTestView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment