Created
October 31, 2023 07:41
-
-
Save jaclync/c97ab04916ee72c09f60d01bc0ca2c03 to your computer and use it in GitHub Desktop.
Binding a SwiftUI Picker selection to an ObservedObject's @published var
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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