UILabel Text Shadow Example in Swift

In this Swift tutorial, you will learn how to add shadow to a text on UILabel in Swift. The Swift code example below adds a shadow to a text on UILabel as well as set shadow offset, opacity, radius, and shadow color.

Create UILabel Programmatically

Before we can set a shadow to a text on UILabel we will first need to create one. The below code Swift code snippet creates a very simple UILabel programmatically.

let label = UILabel()
label.frame = CGRect(x: 20, y: 20, width: 200, height: 20)
label.text = "Text on my label"

Add Shadow, Offset, Opacity, Shadow Color

Now when we have created a simple UILabel, sets add to its text a shadow, offset, opacity, radius, and color.

label.layer.shadowOffset = CGSize(width: 3, height: 3)
label.layer.shadowOpacity = 0.8
label.layer.shadowRadius = 2
label.layer.shadowColor = CGColor.init(srgbRed: 1, green: 0, blue: 0, alpha: 1)

Complete Code Example in Xcode Playground

Below is how the above code example looks and works in my Xcode Playground.

import PlaygroundSupport

class MyViewController : UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let view = UIView()
        view.backgroundColor = .white
        
        let label = UILabel()
        label.frame = CGRect(x: 20, y: 20, width: 200, height: 20)
        label.text = "Text on my label"
 
        label.layer.shadowOffset = CGSize(width: 3, height: 3)
        label.layer.shadowOpacity = 0.8
        label.layer.shadowRadius = 2
        label.layer.shadowColor = CGColor.init(srgbRed: 1, green: 0, blue: 0, alpha: 1)
        
        view.addSubview(label)
        self.view = view
    }
    
}

PlaygroundPage.current.liveView = MyViewController()

UILabel Text Shadow Example in Swift

I hope this tutorial was of some aid to you. There are many other Swift tutorials on this site if you look around. To find more tutorials related to UILabel, check the UILabel tutorials category.

Happy learning! 🙋🏻‍♂️

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!