How to create border in UIButton?

前端 未结 12 1522
天命终不由人
天命终不由人 2020-12-02 05:51

I use custom button in my app named \"addButton\" and I want to border it with white color how can i get the white color border around my custom button?

12条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 06:47

    Here's a UIButton subclass that supports the highlighted state animation without using images. It also updates the border color when the view's tint mode changes.

    class BorderedButton: UIButton {
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            layer.borderColor = tintColor.CGColor
            layer.borderWidth = 1
            layer.cornerRadius = 5
    
            contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("NSCoding not supported")
        }
    
        override func tintColorDidChange() {
            super.tintColorDidChange()
    
            layer.borderColor = tintColor.CGColor
        }
    
        override var highlighted: Bool {
            didSet {
                let fadedColor = tintColor.colorWithAlphaComponent(0.2).CGColor
    
                if highlighted {
                    layer.borderColor = fadedColor
                } else {
                    layer.borderColor = tintColor.CGColor
    
                    let animation = CABasicAnimation(keyPath: "borderColor")
                    animation.fromValue = fadedColor
                    animation.toValue = tintColor.CGColor
                    animation.duration = 0.4
                    layer.addAnimation(animation, forKey: "")
                }
            }
        }
    }
    

    Usage:

    let button = BorderedButton(style: .System) //style .System is important

    Appearance:

提交回复
热议问题