【问题标题】:Shadow not visible on top of "sibling" view阴影在“兄弟”视图顶部不可见
【发布时间】:2018-06-13 20:26:56
【问题描述】:

我正在尝试在视图顶部创建阴影。
这是我的层次结构:
视图
------TablewView
------底部视图

TableView 和 BottomView 具有相同的父级:View。
我希望 BottomView 在 TableView 顶部有一个阴影,就像左边的图片一样,但结果是右边的那个:

如果我尝试删除 TableView,我会看到阴影。 BottomView 有圆角。 这是 BottomView 类:

class BottomView: UIView {
    private var shadowLayer: CAShapeLayer!

    override func layoutSubviews() {
        super.layoutSubviews()

        if shadowLayer == nil {
            let shadowLayer = CAShapeLayer()
            shadowLayer.masksToBounds = false
            //rect is an ex.
            shadowLayer.path =  UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 200, height: 80), cornerRadius: 9).cgPath
            shadowLayer.fillColor = UIColor.red.cgColor

            shadowLayer.shadowColor = UIColor.black.cgColor
            shadowLayer.shadowPath = shadowLayer.path
            shadowLayer.shadowOffset = CGSize(width: 5, height: -5)
            shadowLayer.shadowOpacity = 1
            shadowLayer.shadowRadius = 3
            shadowLayer.zPosition = 10
            layer.insertSublayer(shadowLayer, at: 0)
            clipsToBounds = false
        }
    }
}

【问题讨论】:

    标签: ios swift uiview shadow cashapelayer


    【解决方案1】:

    第一个问题是变量/对象范围...

    class BottomView: UIView {
        private var shadowLayer: CAShapeLayer!
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            if shadowLayer == nil {
                let shadowLayer = CAShapeLayer()
                ...
    

    你在哪里说:let shadowLayer = CAShapeLayer(),你刚刚创建了一个新的本地 shadowLayer 对象,当它超出范围时它会消失(最后if 块)。

    将该行更改为:

    shadowLayer = CAShapeLayer()   // remove the let
    

    你应该看到你的影子。

    您可以通过在if 块下方添加以下内容来“自动”调整大小:

        if shadowLayer != nil {
            shadowLayer.path =  UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height), cornerRadius: 9).cgPath
        }
    

    这将在视图更改大小时重新调整阴影层的大小。

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2012-03-18
      • 2014-07-30
      相关资源
      最近更新 更多