Swift - Problems with corner radius and drop shadow

前端 未结 14 1443
失恋的感觉
失恋的感觉 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:50

    To expand on Imanou's post, it's possible to programmatically add the shadow layer in the custom button class

    @IBDesignable class CustomButton: UIButton {
        var shadowAdded: Bool = false
    
        @IBInspectable var cornerRadius: CGFloat = 0 {
            didSet {
                layer.cornerRadius = cornerRadius
                layer.masksToBounds = cornerRadius > 0
            }
        }
    
        override func drawRect(rect: CGRect) {
            super.drawRect(rect)
    
            if shadowAdded { return }
            shadowAdded = true
    
            let shadowLayer = UIView(frame: self.frame)
            shadowLayer.backgroundColor = UIColor.clearColor()
            shadowLayer.layer.shadowColor = UIColor.darkGrayColor().CGColor
            shadowLayer.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: self.cornerRadius).CGPath
            shadowLayer.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
            shadowLayer.layer.shadowOpacity = 0.5
            shadowLayer.layer.shadowRadius = 1
            shadowLayer.layer.masksToBounds = true
            shadowLayer.clipsToBounds = false
    
            self.superview?.addSubview(shadowLayer)
            self.superview?.bringSubviewToFront(self)
        }
    }
    

提交回复
热议问题