ios - UIButton NSAttributedString 不会更新字体颜色

标签 ios swift nsattributedstring nsmutablestring

我正在尝试将 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!)

最佳答案

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

关于ios - UIButton NSAttributedString 不会更新字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55284616/

相关文章:

ios - popViewController 在 iOS 中的 NSURLSessionDataTask block 中不起作用

swift - 如何从 FBSDKGraphRequest 结果将用户名设置为 UITextField

ios - 将 2 个 NSAttributedStrings 放在一个标签中

nsattributedstring - Super/Subscript 似乎在 iOS13 中被破坏 (NSAttributedString)

ios - 如何使用属性字符串设置最小字体大小或最小比例因子(ios 7)?

iphone - 为什么我的Xcode 4.6 本地化文件只能选择英文?

ios - GPUImage 在使用 iPhone 前置摄像头时出现垂直黑条

ios - 如何在 Afnetwoking post 方法中将数组作为参数发送?

ios - 将多维字符串数组转换为 double

Swift 协议(protocol)继承无法编译