阴影未出现Swift 4.2

Shadow is not appearing Swift 4.2

我正在尝试使用 swift 向按钮添加投影。我已经以编程方式在这个视图控制器上创建了元素,我觉得这就是为什么没有出现阴影的原因,因为阴影出现在我在应用程序中拥有的其他视图控制器中。我也尝试过处理 clipToBounds 和 maskToBounds 但无法修复。我错过了什么?

这是我用来尝试让阴影出现的代码。

let dateLabelButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false

    button.layer.cornerRadius = 10
    button.backgroundColor = Colours().brightRedColour

    button.addTarget(self, action: #selector(segueToPopUp), for: .touchUpInside)

    let shadow = UIBezierPath(roundedRect: button.bounds, cornerRadius: 10).cgPath
    button.layer.shadowRadius = 5
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOpacity = 1
    button.layer.masksToBounds = false
    button.layer.shadowPath = shadow

    return button
}()

这是我添加到此按钮的约束条件。

// Sets up layout for date label button
    dateLabelButton.bottomAnchor.constraint(equalTo: self.view.topAnchor, constant: self.view.frame.height * 2/3 - 50).isActive = true
    dateLabelButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
    dateLabelButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
    dateLabelButton.topAnchor.constraint(equalTo: barChart.bottomAnchor, constant: 10).isActive = true
    dateLabelButton.heightAnchor.constraint(equalToConstant: 40).isActive = true

任何帮助都会很棒,我已经尝试了几个小时了,但我就是想不通。

我认为这会奏效。

let dateLabelButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false

    button.layer.cornerRadius = 10
    button.backgroundColor = Colours().brightRedColour

    button.addTarget(self, action: #selector(segueToPopUp), for: .touchUpInside)

    //let shadow = UIBezierPath(roundedRect: button.bounds, cornerRadius: 10).cgPath
    button.layer.shadowRadius = 5
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
    button.layer.shadowOpacity = 1.0
    button.layer.masksToBounds = false
   // button.layer.shadowPath = shadow

    return button
}()

如果您使用 UIBezierPath 作为阴影,则需要在 viewDidLayoutSubviews() 内进行,如下所示:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let shadow = UIBezierPath(roundedRect: dateLabelButton.bounds, cornerRadius: 10).cgPath
    dateLabelButton.layer.shadowRadius = 5
    dateLabelButton.layer.shadowColor = UIColor.black.cgColor
    dateLabelButton.layer.shadowOpacity = 1
    dateLabelButton.layer.masksToBounds = false
    dateLabelButton.layer.shadowPath = shadow
}

否则,您可以像 Enea 的回答一样注释掉您的 shadowPath