iosswiftnsattributedstringnsattributedstringkey

How to set NSAttributedString text color?


I tried to set some attributes to an NSAttributedString. Everything works except for the foreground color.

This is how I tried to set the attributes:

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)
}

As you can see in the image it does not set the text color:

enter image description here

Do you know why it ignores the foregroundColor attribute?

Thanks in advance.


Solution

  • Your problem is on the strokeWidth property, because you are using a positive number only the stroke is affected. You need to use a negative number to change stroke and fill the text, as stated on the documentation of the strokeWidth property:

    Specify positive values to change the stroke width alone. Specify negative values to stroke and fill the text.

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

    In my opinion, it's also better to specify the data type of the list instead of casting a list to that type specific type.