UIButton bottom shadow

后端 未结 11 1164
-上瘾入骨i
-上瘾入骨i 2020-12-12 14:14

I have a UIButton which is very similar to the standard iOS keyboard alphabet button.

I am not sure how to create a shadow only for the bottom layer li

11条回答
  •  臣服心动
    2020-12-12 14:55

    CornerRadius and shadow don't mix well on the same layer. So you will have to embed your "to be cornered" UIButton inside an UIView. The shadow will be applied on this UIView.

    The following code, given as an example, produces the image below it:

    import UIKit

    class CustomButton: UIButton {
    
        required init(coder decoder: NSCoder) {
            super.init(coder: decoder)
    
            backgroundColor = UIColor.whiteColor()
        }
    
        override func drawRect(rect: CGRect) {
            updateLayerProperties()
        }
    
        func updateLayerProperties() {
            layer.masksToBounds = true
            layer.cornerRadius = 12.0
    
            //superview is your optional embedding UIView
            if let superview = superview {
                superview.backgroundColor = UIColor.clearColor()
                superview.layer.shadowColor = UIColor.darkGrayColor().CGColor
                superview.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 12.0).CGPath
                superview.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
                superview.layer.shadowOpacity = 1.0
                superview.layer.shadowRadius = 2
                superview.layer.masksToBounds = true
                superview.clipsToBounds = false
            }
        }
    
    }
    

提交回复
热议问题