自定义 UILabel 在 Interface Builder 中显示不正确

Custom UILabel not displaying properly in Interface Builder

我有一个基于 class 的自定义 UILabel,它无法在故事板中正确显示。

它只显示一个空白标签。 XCode 6 和 7 beta 都会发生这种情况。

import UIKit

@IBDesignable


class CCLabel: UILabel {

@IBInspectable var spacingChar: CGFloat = 0 {
    didSet {
        self.updateAttributed(self.text)
    }
}

@IBInspectable var extraLineSpacing: CGFloat = 0 {
    didSet {
        self.updateAttributed(self.text)
    }
}

override var bounds: CGRect {
    didSet {
        if (bounds.size.width != self.bounds.size.width) {
            self.setNeedsUpdateConstraints()
        }
        super.bounds = bounds
    }
}

override func updateConstraints() {
    if (self.preferredMaxLayoutWidth != self.bounds.size.width) {
        self.preferredMaxLayoutWidth = self.bounds.size.width
    }
    super.updateConstraints()
}

override var text: String? {
    didSet {
        if let txt = text {
            self.updateAttributed(txt)
        }
    }
}

private func updateAttributed(text: String?) {

    if (text == nil) {
        return
    }

    if (extraLineSpacing > 0 || spacingChar > 0) {

        let attrString = NSMutableAttributedString(string: text!)
        let rng = NSMakeRange(0, attrString.length)

        if (extraLineSpacing > 0) {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = extraLineSpacing
            paragraphStyle.alignment = self.textAlignment

            attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:rng)
        }
        if (spacingChar > 0) {
            attrString.addAttribute(NSKernAttributeName, value:spacingChar, range:rng)
        }

        attrString.addAttribute(NSFontAttributeName, value: self.font, range: rng)

        self.attributedText = attrString

    }
}
}

这是 IB 中的自定义 UILabel class:

当我删除自定义 class 标签的名称时,它可以正常显示。

当我再次添加它时,它并没有消失。然而,下一次又是白色的。

当您 运行 项目时,它是完美的。我想 XCode 没有正确渲染它,但不知道为什么。

我认为你需要这样称呼:

[超级drawRect:rect];

当您对 UIView 以外的任何子类进行子类化时,您应该在实现中调用 super.draw( _ ...)。 (https://developer.apple.com/documentation/uikit/uiview/1622529-drawrect)