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

时间:2017-09-20 05:41:12

标签: uisegmentedcontrol uicolor ios11 uifont swift4

我想从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"
}

1 个答案:

答案 0 :(得分:2)

TintColor附加

  • 所选细分的背景色,

  • 未选定细分的文字颜色和

  • UISegmentedControl的边框颜色。

因此,如果您要将tintColor更改为白色,那么背景颜色和色调两者都将消失。

您需要设置如下所示的选定/未选定文字属性:

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)