【问题标题】:UIButton NSAttributedString won't update font colorUIButton NSAttributedString 不会更新字体颜色
【发布时间】:2019-08-12 13:19:09
【问题描述】:

我正在尝试将string 放在同时具有小图像和文本的按钮上,因此我使用NSMutableAttributedStringNSAttributedString。据我所知,字典中的foregroundColor 键应该更新文本的颜色,但它似乎不起作用。 fgColor 是 UIColor.white 和 bgColor 是 UIColor.black 但我无法打印出来验证。任何人都可以提供建议吗?代码是:

let myFont = UIFont(name: "HelveticaNeue-Light", size: 8)
let dict1:[NSAttributedString.Key:Any] = [
        NSAttributedString.Key.font:myFont!,
        NSAttributedString.Key.foregroundColor : fgColor,
        NSAttributedString.Key.strokeColor : fgColor,
        NSAttributedString.Key.backgroundColor : bgColor
]
let fullString = NSMutableAttributedString()
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named:"ThumbsUpGreen")
let imageString = NSAttributedString(attachment: imageAttachment)
fullString.append(imageString)
fullString.append(NSAttributedString(string: " "+String(upCount), attributes: dict1))
thumbUpButton?.setAttributedTitle(fullString, for: .normal)
contentView.addSubview(thumbUpButton!)

【问题讨论】:

    标签: ios swift nsattributedstring nsmutablestring


    【解决方案1】:

    如果您不打算在文本中使用不同的颜色,作为替代方案,您可以使用 UIButton 的方法来着色: thumbUpButton?.titleLabel?.textColor = fgColor thumbUpButton?.backgroundColor = bgColor

    【讨论】:

    • 谢谢。那行得通。这些按钮位于 TableViewCell 上,该 TableViewCell 位于 TabController 的一个选项卡上的 ViewController 上。现在我必须弄清楚用户何时切换到另一个选项卡并更改背景颜色,然后切换回此选项卡,如何更新 TableViewCell 中按钮的标题标签。
    • 回答我之前对这里阅读的任何人的评论:TableViewCells 在视图再次出现时被重用。但是,tableview 回调是执行的,因此在使单元格出列并返回“新”单元格的那个中,您可以测试按钮的存在,如果按钮已经存在,则更新它的 titleLabel(在我的情况下是这样。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2021-09-30
    相关资源
    最近更新 更多