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

Dav*_*vid 3 uibutton ios swift

我试图让我的按钮在 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()
}

}
Run Code Online (Sandbox Code Playgroud)

应该看到按钮的阴影,而不是我没有阴影。 在此处输入图片说明

Sul*_*han 11

您缺少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
Run Code Online (Sandbox Code Playgroud)

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

btnHi.layer.masksToBounds = false
Run Code Online (Sandbox Code Playgroud)