如何设置 NSAttributedString 文本颜色?

Din*_*lae 0 nsattributedstring ios swift nsattributedstringkey

我尝试将一些属性设置为 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)
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

提前致谢。

Cla*_*dio 7

您的问题出在strokeWidth属性上,因为您使用的正数仅影响笔划。您需要使用负数来更改描边并填充文本,如描边宽度属性的文档中所述:

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

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

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