为什么标记为@IBInspectable的属性不起作用?

时间:2016-10-18 08:33:45

标签: ios swift ibdesignable ibinspectable

我按照tutorial这里创建了一个可检查和可设计的视图。我只想在UIView

中添加边框颜色,边框宽度和圆角边框功能

我成功地展示了这些属性。但是我在故事板上设置的内容并不重要,结果仍然就像他们不在那里一样。即使我将边框设置为宽度为2并且颜色为黑色,也没有边框。它没有在故事板和运行时显示。我已将边框设置为2宽度,但在运行时,我在didViewLoad处打印边框宽度值,结果为0.可能出现什么问题?

@IBDesignable extension view: UIView {

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

    @IBInspectable var borderWidth: CGFloat {
        get {
            return layer.borderWidth;
        }
        set {
            layer.borderWidth = borderWidth;
        }
    }

    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(CGColor: layer.borderColor!);
        }
        set {
            layer.borderColor = borderColor?.CGColor
        }
    }

}

这也不起作用:

@IBDesignable class BOView: UIView {

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

    @IBInspectable var borderWidth: CGFloat {
        get {
            return layer.borderWidth;
        }
        set {
            layer.borderWidth = borderWidth;
        }
    }

    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(CGColor: layer.borderColor!);
        }
        set {
            layer.borderColor = borderColor?.CGColor
        }
    }

}

1 个答案:

答案 0 :(得分:5)

尝试使用newValue而不是实际值。

例如,

@IBInspectable var borderWidth: CGFloat {
    get {
        return layer.borderWidth
    }
    set {
        layer.borderWidth = newValue
    }
}
陈,我更喜欢你这样做的方式,但是请注意,你可以直接从Storyboard直接使用IBDesignable。您可以在“用户定义的运行时属性”中设置图层属性。

enter image description here