是否可以更改 NSAttributedString
颜色而无需再次设置 title
?
我已经尝试过:
for case let i as UIButton in myView.subviews {
if i.backgroundColor != UIColor.greenColor() && i.backgroundColor != UIColor.grayColor() {
i.titleLabel?.textColor = color
// i.setTitleColor(color, forState: .Normal)
// i.setTitleColor(color, forState: .Selected)
// i.tintColor = color
}
}
i.titleLabel.textcolor
更改 .Normal
状态的颜色,但不更改 .Selected
状态
最佳答案
您不能只设置颜色而不设置标题,但可以使用 attributedTitleForState(.Selected)
并访问其字符串属性来完成此操作。您还可以创建自己的 setAttributedTitleColor 方法来扩展 UIButton,如下所示:
extension UIButton {
func setAttributedTitleColor(color: UIColor, forState: UIControlState) {
guard let title = attributedTitleForState(forState)?.string else { return }
setAttributedTitle(NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : color]), forState: forState)
}
}
关于ios - 更改 NSAttributedString 文本颜色而无需再次设置标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34657269/