简体   繁体   中英

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.

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

layer.shadowOpacity = 0.5

Badda bing badda boom.

您需要设置阴影路径,假设它位于uibutton扩展中

self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 20).CGPath

For someone, like me, who might still face the same issue even if layer.shadowOpacity is set to a non-zero value. If your button background color is UIColor.clear, you should change it to other colors, eg white color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM