Search code examples
iosswiftxcodelabeloutline

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


Solution

  • 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