以编程方式设置IBInspectable

时间:2016-12-03 13:26:48

标签: ios swift storyboard ibinspectable

我想根据我得到的互联网信息设置不同的IBInspectable项目。例如,我有绿色,红色和橙色圆圈的IBInspectables。如果请求显示为绿色,我想将isGreen设置为Yes,其他设置为no。其他两个也是如此。 你可以看到IBInspectables here。我知道我可以使用我已经放入的代码来实现它,但有没有办法以编程方式切换它们?

2 个答案:

答案 0 :(得分:3)

任何IBInspectable,仅仅是编码为在IB中看到的属性。所以如果你有这个:

@IBInspectable var isGreen:Bool? {
    didSet {
        // code to color circle?
    }
}

你可以这样做:

self.isGreen = true

答案 1 :(得分:0)

你听起来很困惑。术语IBInspectable描述了视图对象的属性,其上包含@IBInspectable标记。这告诉Interface Builder您希望能够从Interface Builder内部更改该属性。

除了可以从Interface Builder中编辑外,IBInspectable属性与任何其他属性没有区别。

如果您有一个CircleView类,其属性直径为:

class FooView: UIView {
  @IBInspectable var diameter: CGFloat {
    didSet {
      //Code to do something with a change to the diameter property
    }
}

并且您的视图控制器中有一个带有插座的FooView对象,然后您可以像在任何其他属性中一样在代码中更改自定义属性的值:

class MyViewController: UIViewController {

  @IBOulet weak var fooView: FooView!

  @IBAction func buttonTapped(sender: UIButton) {
    fooView.diameter += 5
  }
}