Below I have the code for my picker:
struct pickerSwitch: View {
@ObservedObject var appState: AppState
@State var selection: String = "Red"
var colors = ["Red", "Blue"]
init(appState: AppState) {
print("Init ran again")
self.appState = appState
if appState.showBlueControl {
UISegmentedControl.appearance().setTitleTextAttributes([.font : UIFont.preferredFont(forTextStyle: .headline)], for: .normal)
UISegmentedControl.appearance().backgroundColor = .blue
} else {
UISegmentedControl.appearance().setTitleTextAttributes([.font : UIFont.preferredFont(forTextStyle: .headline)], for: .normal)
UISegmentedControl.appearance().backgroundColor = .red
}
}
var body: some View {
Picker(selection: $selection, label: Text("")) {
ForEach(colors, id: \.self) {
Text($0)
}
}.pickerStyle(SegmentedPickerStyle())
}
}
Elsewhere in my code, I have a button that changes the value of 'showBlueControl' for the specific instance of 'AppState.' In my Xcode logs, I see lots of the 'Init ran again' log so I thought the segmented control should be changing but for some reason the change only takes places when I close the view entirely and reopen it. How can I dynamically change the SegmentedControl when there is a SwiftUI state change (w/o closing/reopening the view)?
You just need an
@Stateto keep track of the background color. Then you set the.background()on the picker. To change your state variable, simply use.onChange.