Swift - Problems with corner radius and drop shadow

前端 未结 14 1468
失恋的感觉
失恋的感觉 2020-11-28 18:35

I\'m trying to create a button with rounded corners and a drop shadow. No matter how I switch up, the button will not display correctly. I\

14条回答
  •  余生分开走
    2020-11-28 18:56

    Refactored this to support any view. Subclass your view from this and it should have rounded corners. If you add something like a UIVisualEffectView as a subview to this view you likely need to use the same rounded corners on that UIVisualEffectView or it won't have rounded corners.

    /// Inspiration: https://stackoverflow.com/a/25475536/129202
    class ViewWithRoundedcornersAndShadow: UIView {
        private var theShadowLayer: CAShapeLayer?
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            if self.theShadowLayer == nil {
                let rounding = CGFloat.init(22.0)
    
                let shadowLayer = CAShapeLayer.init()
                self.theShadowLayer = shadowLayer
                shadowLayer.path = UIBezierPath.init(roundedRect: bounds, cornerRadius: rounding).cgPath
                shadowLayer.fillColor = UIColor.clear.cgColor
    
                shadowLayer.shadowPath = shadowLayer.path
                shadowLayer.shadowColor = UIColor.black.cgColor
                shadowLayer.shadowRadius = CGFloat.init(3.0)
                shadowLayer.shadowOpacity = Float.init(0.2)
                shadowLayer.shadowOffset = CGSize.init(width: 0.0, height: 4.0)
    
                self.layer.insertSublayer(shadowLayer, at: 0)
            }
        }
    }
    

提交回复
热议问题