阴影未出现Swift 4.2

时间:2019-01-18 10:55:16

标签: ios swift autolayout calayer

我正在尝试快速为按钮添加阴影。我已经以编程方式在此视图控制器上创建了元素,我有一种感觉,这就是为什么阴影没有出现的原因,因为阴影出现在应用程序中的其他视图控制器中。我也尝试过处理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

任何帮助都将是非常有用的,我已经尝试了几个小时,但我仍然无法解决。

2 个答案:

答案 0 :(得分:3)

如果您使用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

答案 1 :(得分:2)

我认为这会起作用。

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