使用IBInspectable在选定状态下的UIButton边框颜色

时间:2015-06-22 22:45:07

标签: ios swift uibutton swift-extensions ibinspectable

我使用@IBInspectable使用Swift扩展程序在UIButton上设置边框颜色,如下所示:

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

...但我还想为按钮的selectedBorderColor状态设置.Selected属性。这可能是这样的扩展吗?我是否必须继承UIButton并以某种方式检查按钮状态?

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
    }
  }
}

提前致谢。

1 个答案:

答案 0 :(得分:5)

您可以像这样继承UIButton

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
            }
        }
    }
}

并使用button.selected = true