Adrian Adrian - 2 months ago 12
iOS Question

UIButton shadow not drawing

I'm attempting to create a method to configure buttons in an app. My method performs as expected, but the shadows don't draw. It does not crash.

I've created a

UIButton
extension
with the following method:

func configureWhiteText(withBackgroundColor buttonColor: UIColor?) {
// basic configuration
tintColor = UIColor.white
setTitleColor(UIColor.white, for: .normal)
backgroundColor = buttonColor

// layer stuff
layer.drawsAsynchronously = true
layer.shouldRasterize = true
layer.cornerRadius = 10.0
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 5.0, height: 5.0)
layer.shadowRadius = 5.0
}


I've tried it within a
UITableViewController
in
viewDidLoad
and 'viewWillAppear` without luck:

myButton.configureWhiteText(withBackgroundColor: UIColor.blue)


The buttons are in grouped static cells of
UITableViewController
. Everything works within the configuration method except the shadow-oriented lines of code.
layer.cornerRadius
rounds the corner as expected, but none of the other
layer
-oriented lines draw a shadow.

I've verified
layer.masksToBounds = false
. I also tried commenting out
layer.drawsAsynchronously
and
layer.shouldRasterize
to no avail.

Any further ideas/suggestions are appreciated.

Answer

You left out the setting that actually turns on the shadow — the shadowOpacity. Add this line:

layer.shadowOpacity = 0.5

Badda bing badda boom.