1

I am using the Picker in SwiftUI with the style of SegmentedPicker.

I am trying to change the colors of the picker and found this code in stackoverflow. How to change selected segment color in SwiftUI Segmented Picker

init() {
    UISegmentedControl.appearance().selectedSegmentTintColor? = .blue
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .normal)
}

But an error pops up saying "Return from initializer without initializing all stored properties"

What can I do to make the error diappear :(

enter image description here

asdfg
  • 57
  • 4

2 Answers2

1

If you're going to call this in the init within LoginSheetView, you also need to set up all of the other variables within the init function.

When you set the UISegmentedControl.appearance(), it is setting the appearance globally across you app for all UISegmentedControls. Since it therefore doesn't need to be called within LoginSheetView, the easy solution would be to move this init to one of your initial views that doesn't have other init variables, such as the ___App.swift file where you @main is called.

nicksarno
  • 3,850
  • 1
  • 13
  • 33
  • Thank you for your help! But I just started learning swiftUI so I am not sure what you mean. So can I just add another .swift file and add a struct of view, and then paste the code above into the struct? or should I put it in an init function located in another struct view where I customized the settings of my navigation bar in another view? – asdfg Nov 25 '20 at 22:40
  • When you created your app, there is a file that gets automatically created titled "[yourappname]App.swift". Within the file, it will probably say "@main" somewhere, which basically means that when you build and run your app to a device, the app's starting point will be that file. You can just put the init function into that file. – nicksarno Nov 26 '20 at 00:01
1

If you provide a own init() method, you have to initialize all your your properties. As almost every property got a default value, you should only have to initialize the Binding to make your code work...

init(showLoginView: Binding<Bool>) {
    self._showLoginView = showLoginView //<< here init your stored properties

    UISegmentedControl.appearance().selectedSegmentTintColor? = .blue
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .normal)
}
davidev
  • 7,694
  • 5
  • 21
  • 56