0

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.

Dinu Nicolae
  • 1,019
  • 2
  • 17
  • 42

1 Answers1

7

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.

Claudio
  • 5,078
  • 1
  • 22
  • 33
  • 1
    Just FYI, you can get rid of the `NSAttributedString.Key` prefix for the dictionary keys when you declare the type like this. – Gereon Sep 27 '20 at 11:00
  • Yes, that's another advantage, makes the code cleaner. I've updated the answer – Claudio Sep 27 '20 at 11:04