Swift how to set default text color for UISegmentedControl?
13,115
Solution 1
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.redColor()], forState: .Selected)
Solution 2
Swift 5+ code to update text color for your UISegmentedControl
(sc
in this example)
// selected option color
sc.setTitleTextAttributes([.foregroundColor: UIColor.green], for: .selected)
// color of other options
sc.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)
Solution 3
Swift 4.2 +
segmentedControl.tintColor = .black //background
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)
Solution 4
Here is the workable one:
// default background color
customSC.backgroundColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)
// selected background color
customSC.tintColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)
// selected title text color
customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.selected)
// default title text color
customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.darkGray], for: UIControlState.normal)
Related videos on Youtube
Comments
-
LF00 over 1 year
I want to set colors for the text and background of UISegmentedControl. So I've four colors to set, the default and selected color of the text and background.
I can use
tintColor
andbackgroundColor
to set the background. But how to set the default text color, not same as the tint color?Note: here is swift3 not the older language. I'm a beginner of ios, I just start from the swift3, have no experience of the former language.
Any help will be appreciated.
-
LF00 about 7 yearsI want to set the default text color.
-
LF00 about 7 yearsI find it, check my answer.