Ios Swift如何为UISegmentedControl设置默认文本颜色?

Ios Swift如何为UISegmentedControl设置默认文本颜色?,ios,swift,iphone,xcode,uisegmentedcontrol,Ios,Swift,Iphone,Xcode,Uisegmentedcontrol,我想为UISegmentedControl的文本和背景设置颜色。所以我要设置四种颜色,文本和背景的默认颜色和选定颜色 我可以使用tintColor和backgroundColor设置背景。但是如何设置默认文本颜色,而不是与着色颜色相同 注意:这里是swift3而不是较旧的语言。我是ios的初学者,我刚从swift3开始,没有前一种语言的经验 任何帮助都将不胜感激。以下是可行的: UISegmentedControl.appearance().setTitleTextAttributes([NSF

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

我可以使用
tintColor
backgroundColor
设置背景。但是如何设置默认文本颜色,而不是与着色颜色相同

注意:这里是swift3而不是较旧的语言。我是ios的初学者,我刚从swift3开始,没有前一种语言的经验


任何帮助都将不胜感激。

以下是可行的:

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.redColor()], forState: .Selected)
    //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 4.2+为您的
UISegmentedControl
更新文本颜色的代码(
sc
,在下面的示例中):


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)

我想设置默认文本颜色。我找到了它,请检查我的答案。我想设置默认文本颜色。虽然此代码段可以解决问题,但确实有助于提高您的文章质量。请记住,您将在将来为读者回答这个问题,而这些人可能不知道您的代码建议的原因。我找到了它,请检查我的答案。
// selected option color
sc.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.green], for: .selected)

// color of other options
sc.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
segmentedControl.tintColor = .black //background
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)