i'm looking for a way to display a UILabel with layer.cornerRadius and layer.shadow.

I figured out, that with label.clipsToBounds = true the cornerRadius will be set and with label.masksToBounds = false the shadow will be displayed

With both only the shadow, without the cornerRadius will be displayed

let label = UILabel()
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 32, weight: .regular)
label.textColor = .white
label.clipsToBounds = true
label.backgroundColor = Colors.Vibrants.softBlue
label.layer.cornerRadius = 50
label.layer.masksToBounds = false
label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowOffset = CGSize(width: 5, height: 5)
label.layer.shadowRadius = 5
label.layer.shadowOpacity = 0.7
label.text = "0"

Can anyone solve this, so that the cornerRadius AND the shadow will be displayed?

3 Answers

1
Community On Best Solutions

Why don't you try adding a parent UIView for your label that will contain the background color and cornerRadius. Then retain the shadow properties to the label

0
Deviyani Swami On
class setShadowOnLabel: UILabel
{
    override func layoutSubviews()
    {
        self.layer.cornerRadius = 5
        self.layer.shadowColor = UIColor.lightGray.cgColor
        self.layer.shadowOffset = CGSize(width: 0.0, height: 0.2)
        self.layer.shadowOpacity = 0.80
        self.layer.shadowRadius = 5.0
        self.layer.masksToBounds = false
    }
}

Then directly assign setShadowOnLabel class to Label.enter image description here

enter image description here

1
Community On
    label.layer.borderWidth = 0.2
    label.layer.borderColor = UIColor.clear.cgColor
    label.layer.shadowColor = UIColor.gray.cgColor
    label.layer.shadowOffset = CGSize(width: CGFloat(1.0), height: CGFloat(2.0))
    label.layer.shadowRadius = 1
    label.layer.shadowOpacity = 0.8
    label.layer.cornerRadius = 5.0
    label.layer.masksToBounds = false