使用 Swift 在 Interface Builder 中创建多个自定义 UILabel

Create multiple custom UILabels in Interface Builder with Swift

我有一个包含多个 Labelsnib/xib 文件。每个标签显然应该有不同的文本,但应该看起来都一样。因此,我创建了一个(非常简单的)CustomLabel class 继承自 UILabel:

import UIKit

class CustomLabel: UILabel {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = self.frame.size.width/2.0
        self.layer.backgroundColor = UIColor.blueColor().CGColor
    }
}

然后我单击 Interface Builder 中的每个标签并将每个自定义 class 设置为此 "CustomLabel",但编译时没有任何变化。

如何正确创建和link自定义元素?

当您调用 init 时,部分视图可能尚未加载。 您可能想在

中进行视图设置
override public func awakeFromNib()
{
    super.awakeFromNib()
    self.layer.cornerRadius = self.frame.size.width/2.0
    self.layer.backgroundColor = UIColor.blueColor().CGColor
}

干杯!

我遇到的问题是我没有调用self.layer.masksToBounds = trueGiving UIView rounded corners,因此圆角没有显示。我仍然不明白为什么self.layer.backgroundColor不显示'但是没有任何效果。