Search code examples
uisegmentedcontrolnsattributedstringkey

How do I change the color of the unselected/normal segment text in an iOS 13 segmented controller?


I am trying to configure an instance of the UISegmentedController class so that I can set the color of the text in the unselected segment from the default of black to white for a two-segment segmented controller. But I can't find any way of doing it. I have tried using the setTitleTextAttributes(_,for:)method but I cannot find a suitable NSAttributedString.Key attribute to change the text color.


Solution

  • This works for me in a playground:

    import UIKit
    import PlaygroundSupport
    
    let seg = UISegmentedControl(items: ["foo", "bar"])
    seg.setTitleTextAttributes([.foregroundColor: UIColor.red], for: .normal)
    seg.setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .selected)
    seg.selectedSegmentIndex = 0
    
    PlaygroundPage.current.liveView = seg