David
David

Reputation: 327

How do I get button shadow working with Swift 4.2?

I am trying to get my button to render a shadow in swift 4.2

I've followed other examples to no avail. What am I missing?

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var btnHi: UIButton!         // Standard button tweeked in view controller
@IBOutlet weak var btnNext: NextButton!     // My custom button via class

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    btnHi.layer.cornerRadius  = btnHi.frame.height / 2
    btnHi.layer.borderWidth   = 3.0
    btnHi.layer.borderColor   = UIColor.darkGray.cgColor

    btnHi.layer.shadowColor   = UIColor.black.cgColor
    btnHi.layer.shadowOffset  = CGSize(width: 0.0, height: 6.0)
    btnHi.layer.shadowRadius  = 8
    btnHi.layer.opacity       = 0.5
    // btnHi.clipsToBounds       = true
    // btnHi.layer.masksToBounds = false
}

@IBAction func btnNext(_ sender: Any) {
    btnNext.setupShakeButton()
}

}

should see a drop shadow for the button instead I get no shadow. enter image description here

Upvotes: 6

Views: 6040

Answers (1)

Sulthan
Sulthan

Reputation: 130200

You are missing shadowOpacity which is zero by default. You should probably not use opacity because that makes the whole button semitransparent.

btnHi.layer.shadowColor = UIColor.black.cgColor
btnHi.layer.shadowOffset = CGSize(width: 0.0, height: 6.0)
btnHi.layer.shadowRadius = 8
btnHi.layer.shadowOpacity = 0.5

Also note that clipping has to be turned off:

btnHi.layer.masksToBounds = false

Upvotes: 14

Related Questions