虽然上面的回答很好,但是它们中的大多数都会错误地获取所选片段内文本的颜色。我创建了一个UISegmentedControl
子类,您可以在iOS 13及之前的设备上使用,并像在iOS 13之前的设备上一样使用属性。
class LegacySegmentedControl: UISegmentedControl {
private func stylize() {
if #available(iOS 13.0, *) {
selectedSegmentTintColor = tintColor
let tintColorImage = UIImage(color: tintColor)
setBackgroundImage(UIImage(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
setBackgroundImage(UIImage(color: tintColor.withAlphaComponent(0.2)), for: .highlighted, barMetrics: .default)
setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
setTitleTextAttributes([.foregroundColor: tintColor!, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .normal)
setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
layer.borderWidth = 1
layer.borderColor = tintColor.cgColor
if let background = backgroundColor {
self.setTitleTextAttributes([.foregroundColor: background, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
} else {
func detectBackgroundColor(of view: UIView?) -> UIColor? {
guard let view = view else {
return nil
}
if let color = view.backgroundColor, color != .clear {
return color
}
return detectBackgroundColor(of: view.superview)
}
let textColor = detectBackgroundColor(of: self) ?? .black
self.setTitleTextAttributes([.foregroundColor: textColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
}
}
}
override func tintColorDidChange() {
super.tintColorDidChange()
stylize()
}
}
fileprivate extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
使用
tintColorDidChange
方法可确保每当片段视图或其底层视图的
tintColor
属性更改时,
stylize
方法都会被调用,这是iOS上的首选行为。
结果:
segmentedControl.backgroundColor = UIColor.white
). 错误号为FB9746071。 - CyberMew