ios - 更改 NSAttributedString 文本颜色而无需再次设置标题

标签 ios swift

是否可以更改 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/

相关文章:

ios - 设置 Navbar hidden = false 不起作用

ios - 照片和视频未保存在我的自定义相册中

ios - 当用户单击 webView 中的 url 或链接时启动 Safari

ios - 基于窗口的应用程序和基于 View 的应用程序有什么区别?

iphone - 使用GPS计算准确的速度

ios - 如何通过 UICollectionViewController (Swift) 中的 didSelectItemAtIndexPath() 方法访问所有单元格

ios - Swift - 源文件中的编辑器占位符

ios - 将 iPhone 的 ALAsset 返回的图像与计算机上的真实图像匹配

ios - 在 NSString 中搜索方括号

swift - Swift 中用于 OAuth 签名的 HMAC-SHA1