Search code examples
swiftuisegmentedcontrolappearance

setEnabled for UISegmentedControl without styling differently


I am using Swift 4, and I'd like to disable a UISegmentedControl during a demonstration, but I do not want it to style it differently while this is happening. For instance, my UISegmentedControl is called saveAsControl, and I disable a segment:

self.saveAsControl.setEnabled(false, forSegmentAt: 0)

But when this happens, I do not want it to change the appearance.


Solution

  • You could use an extension. Alternatively, you could solve this problem using a simple one-liner which sets the text color of your disabled segments to the default tintColor of the segmentedControl:

    let segmentItems = ["one", "two", "three"]
    let mySegmentedControl = UISegmentedControl(items: segmentItems)
    
    UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:mySegmentedControl.tintColor], for: .disabled)
    
    mySegmentedControl.setEnabled(false, forSegmentAt: 0)
    

    Make sure that you are using UISegmentedControl instead of mySegmentedControl since appearance() is a static method of the UISegmentedControl class.

    This is a screenshot of my code when I run it in the playground: enter image description here