删除色调颜色但保留字体颜色 UISegmentedControl

Remove tint color but keep font color UISegmentedControl

我想从 UISegmetedControl 中删除选定的颜色。我知道 tintColor 可以做到这一点,但这也会删除字体颜色。同样使用 kCTForegroundColorAttributeName 将同时删除两者。

旁注我做了一个 UIView 并将其放在所选段上方以显示所选状态。我认为这会更好看。尝试扩展并制作我自己的自定义控件。

public let topLine = UIView()

override func awakeFromNib() {
    super.awakeFromNib()
    self.removeBorders()
    setFont()
    addTopLine()
}

func setFont() {
    let font = UIFont(name: FontTypes.avenirNextUltraLight, size: 22.0)!
    let textColor = UIColor.MyColors.flatWhite
    let attribute = [kCTFontAttributeName:font]
    self.setTitleTextAttributes(attribute, for: .normal)
}

func addTopLine() {
    topLine.backgroundColor = UIColor.MyColors.flatWhite
    let frame = CGRect(x: 7,
                       y: -5,
                       width: Int(self.frame.size.width)/2,
                       height: 2)
    topLine.frame = frame
    self.addSubview(topLine)
}

struct FontTypes {
     static let avenirNextRegular = "AvenirNext-Regular"
     static let avenirLight = "Avenir-Light"
     static let avenirNextUltraLight = "AvenirNext-UltraLight"
}

TintColor 附有

  • 所选段的背景颜色,

  • 未选中段的文本颜色和

  • UISegmentedControl 的边框颜色。

因此,如果您要将 tintColor 更改为白色,那么背景色和淡色都会消失。

您需要设置 Selected/Unselected 文本属性,如下所示:

mySegment.tintColor = .white

let selectedAtrribute = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)]
mySegment.setTitleTextAttributes(selectedAtrribute as [NSObject : AnyObject], for: UIControlState.selected)

let unselected = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)]
mySegment.setTitleTextAttributes(unselected as [NSObject : AnyObject], for: UIControlState.normal)