UIButton Border Color on Selected State using IBInspectable

4k views Asked by At

I am using @IBInspectable to set a border color on a UIButton using a Swift extension like this:

extension UIButton {
  @IBInspectable var borderWidth: CGFloat {
    get {
      return layer.borderWidth
    }
    set {
      layer.borderWidth = newValue
      layer.masksToBounds = newValue > 0
    }
  }
}

...but I also want to have a selectedBorderColor property for the .Selected state of the button. Is this possible with an extension like this? Do I have to subclass UIButton and check the button state somehow instead?

extension UIButton {
  @IBInspectable var borderWidth: CGFloat {
    get {
      return layer.borderWidth
    }
    set {
      layer.borderWidth = newValue
      layer.masksToBounds = newValue > 0
    }
  }
  //This is what I want to do...
  @IBInspectable var selectedBorderWidth: CGFloat {
    get {
      return layer.borderWidth
    }
    set {
      layer.borderWidth = newValue
      layer.masksToBounds = newValue > 0
    }
  }
}

Thanks in advance.

1

There are 1 answers

0
Renatus On

You can subclass UIButton like this:

class SBButton: UIButton {

    @IBInspectable var borderColor : UIColor = UIColor.whiteColor() {
        didSet {
            self.setNeedsDisplay()
        }
    }

    @IBInspectable var selectedBorderColor : UIColor = UIColor.blackColor() {
        didSet {
            self.setNeedsDisplay()
        }
    }

    override var selected: Bool {
        didSet {
            if selected {
                layer.borderColor = selectedBorderColor.CGColor
            } else {
                layer.borderColor = borderColor.CGColor
            }
        }
    }
}

and use button.selected = true