【问题标题】:How to set NSAttributedString text color?如何设置 NSAttributedString 文本颜色?
【发布时间】:2021-01-13 03:57:50
【问题描述】:

我尝试将一些属性设置为 NSAttributedString。除前景色外,一切正常。

这是我尝试设置属性的方式:

func setLabelText(text:String){
    let strokeTextAttributes = [
        NSAttributedString.Key.strokeColor : UIColor.white,
        NSAttributedString.Key.foregroundColor : UIColor.red,
        NSAttributedString.Key.font : UIFont.init(name: "Raleway-ExtraBold", size: 26)!,
        NSAttributedString.Key.strokeWidth : 0.5,
    ]
      as [NSAttributedString.Key : Any]
    label.attributedText = NSMutableAttributedString(string: text, attributes: strokeTextAttributes)
}

正如您在图像中看到的那样,它没有设置文本颜色:

你知道它为什么会忽略foregroundColor属性吗?

提前致谢。

【问题讨论】:

  • 我以为你的图片对我来说是广告????
  • @sekoya 不是广告:D

标签: ios swift nsattributedstring nsattributedstringkey


【解决方案1】:

您的问题出在strokeWidth 属性上,因为您使用的是正数,只有笔画受到影响。您需要使用负数来更改笔划并填充文本,如strokeWidth 属性的文档中所述:

指定正值以单独更改笔划宽度。指定负值来描边和填充文本。

let strokeTextAttributes: [NSAttributedString.Key : Any] = [
    .strokeColor : UIColor.white,
    .foregroundColor : UIColor.red,
    .font : UIFont.init(name: "Raleway-ExtraBold", size: 26)!,
    .strokeWidth : -0.5,
]

在我看来,最好指定列表的数据类型,而不是将列表强制转换为特定类型。

【讨论】:

  • 仅供参考,当您像这样声明类型时,可以去掉字典键的 NSAttributedString.Key 前缀。
  • 是的,这是另一个优点,使代码更干净。我已经更新了答案
猜你喜欢
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 2018-12-24
  • 2011-10-04
  • 1970-01-01
相关资源
最近更新 更多