iosswiftswiftuiuisegmentedcontrolsegment

Change Segment Controller Tint Color in SwiftUI


I am using a segment picker in my app. I want to change the text color of the unselected to white. I searched for the solutions but didn't get any right for me. Here is my code:

struct QuestionView: View {

@State private var selectedIndex = 0
    
    init() {
        
        UISegmentedControl.appearance().backgroundColor = UIColor(named: ColorName.appBlue.rawValue)
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor(named: ColorName.appBlue.rawValue)!], for: .selected)
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.green], for: .normal)
        UISegmentedControl.appearance().setTitleTextAttributes([
            .font : UIFont.preferredFont(forTextStyle: .headline)
        ], for: .normal)
    }

var body: some View {

 VStack(alignment: .leading) {
            
            NavBar(navTitle: "Questionnaire")
            
            HStack {
                
                Text("Is this a live claim?")
                    .font(.custom(InterFont.bold.rawValue, size: 24))
                
                Spacer()
                
                Picker("What is your favorite color?", selection: $selectedIndex) {
                    Text("Yes").tag(1)
                         
                    Text("No").tag(0)
                    
                }
                .pickerStyle(.segmented)
                .frame(width: 130)
                .cornerRadius(40)
                
            }.padding()
            Spacer()
        }
    }
}

From this code,I am getting this:

what I am getting

The tint color changes for the selected one but not for the unselected. I want white color for the unselected one. Here is what I required:

required


Solution

  • The same thing happened to me due to the font property. Please try to remove the last statement that is used to set the font of the Segmentation Controller.

    init() {
            
            UISegmentedControl.appearance().backgroundColor = UIColor(named: ColorName.appBlue.rawValue)
            UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor(named: ColorName.appBlue.rawValue)!], for: .selected)
            UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.green], for: .normal)
    
        }