Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outline UILabel text in UILabel Subclass

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.

like image 419
iji Avatar asked Nov 13 '16 15:11

iji


1 Answers

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

like image 87
Anand Nimje Avatar answered Sep 22 '22 18:09

Anand Nimje