How to add a drop shadow to a UIButton?

后端 未结 5 1001
面向向阳花
面向向阳花 2020-12-02 07:14

I would like to add a drop shadow to a UIButton. I tried to use self.layer.shadow* properties. Those properties work in UIView, but they behave differently in UIButton. I wo

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 07:44

    You can create a subclass and configure its values in Xcode

    Below is an example:

    import UIKit
    import QuartzCore
    
    @IBDesignable
    class CustomButton: UIButton {
    
    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }
    
    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }
    
    @IBInspectable var borderColor: UIColor = UIColor.gray {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }
    
    @IBInspectable var shadowColor: UIColor = UIColor.gray {
        didSet {
            layer.shadowColor = shadowColor.cgColor
        }
    }
    
    @IBInspectable var shadowOpacity: Float = 1.0 {
        didSet {
            layer.shadowOpacity = shadowOpacity
        }
    }
    
    @IBInspectable var shadowRadius: CGFloat = 1.0 {
        didSet {
            layer.shadowRadius = shadowRadius
        }
    }
    
    @IBInspectable var masksToBounds: Bool = true {
        didSet {
            layer.masksToBounds = masksToBounds
        }
    }
    
    @IBInspectable var shadowOffset: CGSize = CGSize(width: 12, height: 12) {
        didSet {
            layer.shadowOffset = shadowOffset
        }
    }
    
    
     }
    

提交回复
热议问题