I have a question about changing SwiftUI segment picker colors.
struct SwithBarView: View {
//@State private var preselectedIndex = 0
@Binding var preselectedIndex: Int
@State private var selection = ["Selection1", "Selection2"]
init() {
UISegmentedControl.appearance().selectedSegmentTintColor = .green
UISegmentedControl.appearance().backgroundColor =
UIColor(Color.green.opacity(0.3))
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor(Color.blue)], for: .selected)
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor(Color.secondary)], for: .normal)
}
var body: some View {
VStack {
Picker("You Selection", selection: $preselectedIndex) {
ForEach(selection.indices, id: \.self) { index in
Text(selection[index])
.tag(index)
.foregroundColor(Color.theme.accent)
}
}
.pickerStyle(SegmentedPickerStyle())
}
.padding()
}
}
The code works well if I remove the init() closure. But with the init() part, an error message shows up "Return from initializer without initializing all stored properties". I think that is due to the @Binding variable. Is there any method to fix this error? Thanks!
Your binding is not initialised, so you have to add it in init arguments, like
struct SwithBarView: View {
@Binding var preselectedIndex: Int
@State private var selection = ["Selection1", "Selection2"]
init(preselectedIndex: Binding<Int>) {
self._preselectedIndex = preselectedIndex // << here !!
// ... other code