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

Che*_*ong 0 ios swift ibdesignable ibinspectable

我按照这里的教程创建了一个可检查和可设计的视图.我只想添加边框颜色,边框宽度和圆角边框功能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
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

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

}
Run Code Online (Sandbox Code Playgroud)

Car*_*Zyl 5

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

例如,

@IBInspectable var borderWidth: CGFloat {
    get {
        return layer.borderWidth
    }
    set {
        layer.borderWidth = newValue
    }
}
Run Code Online (Sandbox Code Playgroud)

陈,我更喜欢你这样做的方式,但是请注意,你可以直接从Storyboard直接使用IBDesignable.您可以在"用户定义的运行时属性"中设置图层属性.

在此输入图像描述