如何在Swift 4.2中使用按钮阴影?

时间:2019-02-13 19:45:34

标签: ios swift uibutton

我试图让我的按钮在Swift 4.2中渲染阴影

我没有遵循其他示例。我想念什么?

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()
}

}

应该看到按钮的阴影,但是我没有阴影。 enter image description here

1 个答案:

答案 0 :(得分:1)

您缺少shadowOpacity,默认情况下该数字为零。您可能不应该使用opacity,因为这会使整个按钮变成半透明的。

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

还请注意,必须关闭剪辑:

btnHi.layer.masksToBounds = false