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

22
我想为UISegmentedControl设置文字和背景颜色。我有四种颜色要设置,分别是默认和选中状态下的文字和背景颜色。
我可以使用 tintColorbackgroundColor 来设置背景颜色。但是如何设置默认文字颜色,而不是与tint color相同? 注意:这里采用的是Swift 3而不是旧版本语言。我是iOS的初学者,从Swift 3开始入手,没有任何以前语言的经验。
非常感谢您的任何帮助。
6个回答

35

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)

应该添加 "NSAttributedString.Key.foregroundColor" 而不是 ".foregroundColor"。 - emrcftci
@emrcftci 这并不是必需的,但你可以这样做 :) - budiDino

19

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)

19
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.redColor()], forState: .Selected)

我想设置默认文本颜色。 - LF00
我找到了它,检查我的答案。 - LF00

6

这是可行的方案:

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

0

这里有一个在Storyboard上快速处理它的方法:

extension UISegmentedControl {
@IBInspectable var textSelectedColor: UIColor {
    get {
        return self.textSelectedColor
    }
    set {
        self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: newValue], for: .selected)
    }
}

@IBInspectable var textNormalColor: UIColor {
    get {
        return self.textNormalColor
    }
    set {
        self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: newValue], for: .normal)
    }
}}

0
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

我想设置默认文本颜色。 - LF00
虽然这段代码片段可能解决了问题,但包括解释真的有助于提高您的帖子质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您的代码建议原因。 - DimaSan
1
我找到了它,检查我的答案。 - LF00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接