如何设置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)
}

您可以在图像中看到它没有设置文本颜色

enter image description here

您知道为什么它忽略了前台颜色属性吗?

谢谢。

解决方法

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

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

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

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