首页 > 解决方案 > 如何设置 NSAttributedString 文本颜色?

问题描述

我试图将一些属性设置为 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 属性吗?

提前致谢。

标签: iosswiftnsattributedstringnsattributedstringkey

解决方案


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

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

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

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


推荐阅读