如何更改 UISegmentedControl 的一个特定片段的文本颜色?我想让它们保持正常,除了特定的部分应该是不同的颜色,无论它是否被选择。
@IBDesignable
class DesignableSegmentControl: UISegmentedControl{
}
extension UISegmentedControl{
@IBInspectable
var textColor: UIColor{
get {
return self.textColor
}
set {
let unselectedAttributes = [NSAttributedString.Key.foregroundColor: newValue,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)]
self.setTitleTextAttributes(unselectedAttributes, for: .normal)
self.setTitleTextAttributes(unselectedAttributes, for: .selected)
}
}
}
只需更改分段控件的类名,如下所示:
对于 Swift 5:
segmentControl.setTitleTextAttributes( [NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
没有任何内置方式;正如您可能已经发现的那样,
setTitleTextAttributes
适用于所有细分。您必须将文本绘制为图像并使用它。
更新了 Swift 4.1
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
斯威夫特3.1
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)
对于早期 Swift 版本:
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected)
您可以实现自己的分段控件进行定制。
这样定制的空间就很大。 GitHub 上还提供了许多自定义分段控件。 你可以试试这个
只需添加这行代码:
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)