How to make a drop shadow effect on a label in Swift?

UILabel has a property for changing its shadow, the image below shows the property in attributes inspector and the result.

enter image description here

Result of that effect on label enter image description here


works fine but add shadow to ALL label, not to text.

in this case:

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let shadow = NSShadow()
        shadow.shadowColor = UIColor.blue
        shadow.shadowBlurRadius = 10
        
        let attrs: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 36),
            .foregroundColor: UIColor.red,
            .shadow: shadow
        ]
        
        let s = "MY TEXT"
        let attributedText = NSAttributedString(string: s, attributes: attrs)
        self.label.attributedText = attributedText
    }


}


You will get:

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/CRMpg.png




**note:** You must add attributed string every time, as shadow is an attribute of string, not label, otherwise you can also derive class and override "setText". (keeping attributes inside the object in a a property you can set on init/setter)

You can write an extension and use it. Place the extension code outside of class ViewController.

I like subtle shadow.
enter image description here

extension UILabel {
    func textDropShadow() {
        self.layer.masksToBounds = false
        self.layer.shadowRadius = 2.0
        self.layer.shadowOpacity = 0.2
        self.layer.shadowOffset = CGSize(width: 1, height: 2)
    }

    static func createCustomLabel() -> UILabel {
        let label = UILabel()
        label.textDropShadow()
        return label
    }
}

On your label simply call this method

myLabel.textDropShadow()

Give this a try - you can run it directly in a Playground page:

import UIKit
import PlaygroundSupport

let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 400))

container.backgroundColor = UIColor.lightGray

PlaygroundPage.current.liveView = container

var r = CGRect(x: 40, y: 40, width: 300, height: 60)

let label = UILabel(frame: r)
label.font = UIFont.systemFont(ofSize: 44.0)
label.textColor = .white
label.frame = r
label.text = "Hello Blur"

container.addSubview(label)

label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowRadius = 3.0
label.layer.shadowOpacity = 1.0
label.layer.shadowOffset = CGSize(width: 4, height: 4)
label.layer.masksToBounds = false

Play around with different values for the shadow Color, Opacity, Radius and Offset

Result:

enter image description here

Tags:

Ios

Uilabel

Swift