Outline UILabel text in UILabel Subclass

iji picture iji · Nov 13, 2016 · Viewed 12.3k times · Source

I'm trying hard to find a way to simply add an outline/stroke/contour to my UILabel text. Talking about a stroke around the letters of the text not around the background of a UILabel.

I'm using swift 3 and I'd like to outline my text directly into my subclass: UILabel.

I found multiple answers suggesting this way to do things :

let strokeTextAttributes = [
        NSStrokeColorAttributeName : UIColor.black,
        NSForegroundColorAttributeName : UIColor.white,
        NSStrokeWidthAttributeName : -4.0,
        NSFontAttributeName : UIFont.boldSystemFont(ofSize: 30)
    ]

    self.attributedText = NSMutableAttributedString(string: self.text!, attributes: strokeTextAttributes)

But the thing is that it doesn't work. My text is still the same with no outline...

Could anyone help me here ? That would be a great thing :)

Thanks a lot. Cheers guys.

Answer

Anand Nimje picture Anand Nimje · Nov 13, 2016

This code works for me.

Swift 3

let strokeTextAttributes = [
  NSStrokeColorAttributeName : UIColor.black,
  NSForegroundColorAttributeName : UIColor.white,
  NSStrokeWidthAttributeName : -4.0,
  NSFontAttributeName : UIFont.boldSystemFont(ofSize: 30)
] as [String : Any]

myLabel.attributedText = NSMutableAttributedString(string: "Test me i have color.", attributes: strokeTextAttributes)

Output like this...



Swift 4.2 & 5.1

let strokeTextAttributes = [
  NSAttributedString.Key.strokeColor : UIColor.red,
  NSAttributedString.Key.foregroundColor : UIColor.white,
  NSAttributedString.Key.strokeWidth : -4.0,
  NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 30)]
  as [NSAttributedString.Key : Any]

labelOutLine.attributedText = NSMutableAttributedString(string: "Your outline text", attributes: strokeTextAttributes)

enter image description here