使用IBDesignable和prepareForInterfaceBuilder与UILabel一起使用

10

我有一个名为MyViewUIView子类。

它里面有一个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?
    }

}

IBInspectable

在IB中,我可以看到颜色属性并设置它。但很烦人的是,默认值为`.clearColor()`而不是我在代码中设置的颜色。有没有办法解决这个问题?

IBDesignable

当我将视图放入InterfaceBuilder中时,它显示所有可检查属性,但实际视图中没有显示任何内容。

运行后一切都正常工作。我只想能够在IB中获得其他功能(而非drawRect)。尽管文档相当缺乏,但我仍在寻找方法。

Edit - Warnings

我刚注意到我收到了构建错误/警告,内容如下...

警告:IB Designables: 忽略用户定义的运行时属性"UIView"上的关键路径"color"。在试图设置其值时遇到异常:[setValue:forUndefinedKey:]:此类不能用于键值编码-compliant for the key color。

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

3个回答

2
我将您的问题中的代码复制到了一个新应用程序中,添加了视图并设置了属性,它完美地工作了。
您看到的错误表明,在某个时候,您在“身份检查器”中将视图更改回普通的UIView(在这种情况下,用户定义的属性仍然存在)。

目前,当我尝试运行时,出现“分段错误:11”,所以不知道发生了什么。这可能是原因。很高兴知道我的代码是正确的。今天我安装了Xcode 4(原因),所以我想知道这个安装是否对编译器或其他东西进行了修改?!谢谢。不过,我会继续保留我的Swift项目:D - Fogmeister
哦我的天啊!我之前在属性中使用了.clearColor()而不是UIColor.clearColor(),导致了段错误,但代码中没有显示任何错误。不管怎样,现在一切都正常工作了:D 谢谢! - Fogmeister

1
当设置了颜色,您需要使用didSet更新textLabel属性,如下所示。
@IBInspectable var color: UIColor = UIColor.blackColor() {
    didSet {
        textLabel.textColor = color
    }
}

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Fogmeister

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接