Swift:将视图添加到窗口时不显示阴影

时间:2019-03-15 13:56:55

标签: swift

我正在尝试将阴影投射到我的customView上,但未显示。使用window?.addSubview(customView)将此customView添加到窗口中。

到目前为止的实施:

//CustomView setup
lazy var customView: UIView = {
    let v = UIView()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.layer.cornerRadius = 8
    v.layer.shadowColor = UIColor.darkGray.cgColor
    v.layer.shadowOffset = CGSize(width: 0, height: 10)
    v.layer.shadowOpacity = 10.5
    v.layer.shadowRadius = 15.0
    v.layer.masksToBounds = true
    return v
}()

//Adding view to window
window?.addSubview(customView)

NSLayoutConstraint.activate([
    customView.leadingAnchor.constraint(equalTo: window!.leadingAnchor),
    customView.trailingAnchor.constraint(equalTo: window!.trailingAnchor),
    customView.heightAnchor.constraint(equalTo: window!.heightAnchor, multiplier: 1),
    customView.topAnchor.constraint(equalTo: window!.safeAreaLayoutGuide.bottomAnchor, constant: -100)
        ])

我已经遵循了这个post和这个post的建议,但是对于添加到窗口中的视图,它却不会出现。有什么建议吗?谢谢。

2 个答案:

答案 0 :(得分:0)

是因为这一行:

v.layer.masksToBounds = true

如果想要阴影圆角倒圆,我建议使用两层,一层具有阴影和masksToBounds = false,另一层是第一层的子层并具有圆角+ masksToBounds = true

答案 1 :(得分:0)

设置v.clipsToBounds = true之后,然后设置v.layer.masksToBounds = false

您的UIView应该如下所示:

lazy var customView: UIView = {
    let v = UIView()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.layer.cornerRadius = 8
    v.layer.shadowColor = UIColor.darkGray.cgColor
    v.layer.shadowOffset = CGSize(width: 0, height: 10)
    v.layer.shadowOpacity = 10.5
    v.layer.shadowRadius = 15.0
    v.clipsToBounds = true
    v.layer.masksToBounds = false
    return v
}()

注意:有customViewcommentView,请确保您使用的是正确的