How to make a drop shadow effect on a label in Swift?
Give this a try - you can run it directly in a Playground page:
import UIKitimport PlaygroundSupportlet container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 400))container.backgroundColor = UIColor.lightGrayPlaygroundPage.current.liveView = containervar r = CGRect(x: 40, y: 40, width: 300, height: 60)let label = UILabel(frame: r)label.font = UIFont.systemFont(ofSize: 44.0)label.textColor = .whitelabel.frame = rlabel.text = "Hello Blur"container.addSubview(label)label.layer.shadowColor = UIColor.black.cgColorlabel.layer.shadowRadius = 3.0label.layer.shadowOpacity = 1.0label.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:
You can write an extension and use it. Place the extension code outside of class ViewController.
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()