Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an outline to my label in Swift?

I'm new to Stackoverflow.
I am currently developing a mobile application using XCode for iOS.
However I'm trying to set add a white outline/stroke to my label but I do not know hot to. I have tried searching these forums but could not find any solution in swift.
I have tried using the shadow property, but it's not satisfactory.
How do I add an outline to my label in Swift?
Edit: The text should look like the text in this picture: http://cf.chucklesnetwork.com/items/7/5/7/4/4/original/yo-dawg-i-heard-you-like-captions-so-i-put-captions-of-captions.jpg

like image 336
Karliene Avatar asked Jan 23 '26 19:01

Karliene


2 Answers

You need to use NSAttributedString, set strokeColor and strokeWidth to set outline and foregroundColor to set text color. Try this:

let attrString = NSAttributedString(
    string: "Write Something with Outline",
    attributes: [
        NSAttributedStringKey.strokeColor: UIColor.black, 
        NSAttributedStringKey.foregroundColor: UIColor.white, 
        NSAttributedStringKey.strokeWidth: -2.0, 
        NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17.0)
    ]
)
yourLabel.attributedText = attrString

This will look like below:

enter image description here

like image 58
Arnab Avatar answered Jan 26 '26 12:01

Arnab


You can use this OutlinedLabel. Unlike most examples, it actually outlines the text. And you can even gradient the outline.

Just set the outline color and the line width:

label.outlineColor = .white
label.outlineWidth = 7

This will look like this

like image 32
Adriano Avatar answered Jan 26 '26 11:01

Adriano