Why masksToBounds = YES prevents CALayer shadow?

后端 未结 6 1259
借酒劲吻你
借酒劲吻你 2020-11-28 01:44

With the following snippet, I\'m adding a drop shadow effect to one my UIView. Which works pretty well. But as soon as I set the view\'s masksToBounds prope

6条回答
  •  生来不讨喜
    2020-11-28 02:35

    This is the Swift 3 and IBDesignable version of the answer posted by @TheSquad.

    I used the same concept while making changes in the storyboard file. First I moved my targetView (the one which requires corner radius and shadow) inside a new containerView. Then I added the following lines of code (Reference: https://stackoverflow.com/a/35372901/419192) to add some IBDesignable attributes for UIView Class:

    @IBDesignable extension UIView {
    /* The color of the shadow. Defaults to opaque black. Colors created
     * from patterns are currently NOT supported. Animatable. */
    @IBInspectable var shadowColor: UIColor? {
        set {
            layer.shadowColor = newValue!.cgColor
        }
        get {
            if let color = layer.shadowColor {
                return UIColor(cgColor: color)
            }
            else {
                return nil
            }
        }
    }
    
    /* The opacity of the shadow. Defaults to 0. Specifying a value outside the
     * [0,1] range will give undefined results. Animatable. */
    @IBInspectable var shadowOpacity: Float {
        set {
            layer.shadowOpacity = newValue
        }
        get {
            return layer.shadowOpacity
        }
    }
    
    /* The shadow offset. Defaults to (0, -3). Animatable. */
    @IBInspectable var shadowOffset: CGPoint {
        set {
            layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
        }
        get {
            return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
        }
    }
    
    /* The blur radius used to create the shadow. Defaults to 3. Animatable. */
    @IBInspectable var shadowRadius: CGFloat {
        set {
            layer.shadowRadius = newValue
        }
        get {
            return layer.shadowRadius
        }
    }
    
    /* The corner radius of the view. */
    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
        }
        get {
            return layer.cornerRadius
        }
    }
    

    After adding this code, I went back to the storyboard and on selecting my containerView I could now find a new set of attributes in the attributes inspector:

    Other than adding values for these attributes as per my choice, I also added a corner radius to my targetView and set the masksToBounds property as true.

    I hope this helps :)

提交回复
热议问题