我该如何改变 UISegmentedControl 中特定选项卡的文本颜色?我希望所有选项卡都保持正常,除了某个特定的选项卡,无论它是否被选中,都应该是不同的颜色。
我该如何改变 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的内容:
yourSegment.setTitleTextAttributes( [NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
yourSegment
是什么? - undefinedUISegmentedControl
对象。 - undefined没有内置的方法;正如你可能已经发现的那样,setTitleTextAttributes
适用于所有的片段。您需要将文本绘制为图像,然后使用它。
更新 Swift 4.1
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
Swift 3.1
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)
对于早期的Swift版本:
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected)
您可以实现自己的分段控件进行自定义。
通过这种方式,有很大的自定义空间。 此外,GitHub上还有许多自定义分段控件可用。 您可以尝试一下。