我有一个正在创建的名为UIViewMyView子类。

其中有一个UILabel(出于某种原因,该代码未添加到InterfaceBuilder中的代码中)。

然后,我在MyView上拥有一个名为color的属性。

我想要的是让Interface Builder能够选择color,然后显示带有设置为该颜色的字体的标签。

在我的代码中,我有...

@IBDesignable class MyView: UIView {

    private let textLabel = UILabel()

    @IBInspectable var color: UIColor = .blackColor() {
        didSet {
            textLabel.textColor = color
        }
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        initialSetup()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

       initialSetup()
    }

    private func initialSetup() -> Void {
        self.backgroundColor = .clearColor()

        textLabel.textAlignment = .Center
        textLabel.numberOfLines = 0

        addSubview(textLabel)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        textLabel.frame = bounds
    }

    // I have no idea what I'm doing here?!
    override func prepareForInterfaceBuilder() {
        // should I create a label specifically for here?
        // or should I use the property textLabel?

        textLabel.text = "Hello, world!" // setting place holder IB text?
        textLabel.textColor = color
        textLabel.font = .systemFontOfSize(21)
        textLabel.textAlignment = .Center
        textLabel.numberOfLines = 0

        // do I need to add sub view?
    }

}

IB可检查的

在IB中,我可以在那里看到color属性,并且可以对其进行设置。令人讨厌的是,它采用了.clearColor()的默认值,尽管不是我在代码中设置的颜色。有办法解决吗?

IBDesignable

当我将 View 放入InterfaceBuilder中时,它显示了所有可检查的属性,但实际 View 中未显示任何内容。

当我运行它时,一切正常。我只是希望能够在IB中使某些东西正常工作(而drawRect除外)。我发现虽然明显缺乏文档。

编辑-警告

我只是注意到我收到构建错误/警告,说...



这可能会改变解决方案:)

最佳答案

我将您问题中的代码复制到了新的应用程序中,添加了 View 并设置了属性,并且效果很好。

您所看到的错误表明,在某些时候您已将 View 更改回身份检查器中的普通UIView(在这种情况下,用户定义的属性仍然存在)。

关于ios - 将IBDesignable和prepareForInterfaceBuilder与UILabel一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28088343/

10-11 19:59