Swift如何设置UISegmentedControl的默认文字颜色?

Swift how to set default text color for UISegmentedControl?

我想为 UISegmentedControl 的文本和背景设置颜色。所以我有四种颜色要设置,文本和背景的默认颜色和选定颜色。

我可以使用tintColorbackgroundColor设置背景。但是如何设置默认文本颜色,与色调颜色不同?

注意:这里是swift3,不是旧语言。我是初学者ios,刚从swift3入门,对前一种语言没有任何经验。

任何帮助将不胜感激。

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.redColor()], forState: .Selected)
customSC.backgroundColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)
customSC.tintColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)

这是可行的:

// 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)

Swift 5+ 用于更新 UISegmentedControl 文本颜色的代码(本例中为 sc

// selected option color
sc.setTitleTextAttributes([.foregroundColor: UIColor.green], for: .selected)

// color of other options
sc.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)

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)