How to add a shadow behind iOS Buttons in Swift

Nov 10, 2019 07:33 · 184 words · 1 minute read ios ios13 ios14 swift

This will be a super short post but I hope that it will save you some online search. We’ll look at how to add some shadow behind your iOS UIButton. Of course, we’ll do that programatically, using Swift.

There are three attributes you want to set on the UIButton layer field.

shadowColor

The button.layer.shadowColor defines the color of the layer’s shadow. It is black by default but we’ll set it to white here.

button.layer.shadowColor = UIColor.white.cgColor

shadowRadius

The button.layer.shadowRadius defines the size of the layer’s shadow. The default is 3 and it’s usually too small compared to what you want for a clearly visible shadow.

button.layer.shadowRadius = CGFloat(integerLiteral: 6)

shadowOpacity

The button.layer.shadowOpacity defines the opacity of the layer’s shadow. The default value is set to 0.0 (transparent). For this one, you probably want to try and see a few options between 0.0 (transparent) and opaque (1.0).

button.layer.shadowOpacity = Float(floatLiteral: 0.8)

Conclusion

And that’s it! If you set this three attributes and play a little bit with the radius and the opacity, you should be able to see a nice shadow behind your iOS UIButton.

tweet Share