【问题标题】:Custom UILabel not displaying properly in Interface Builder自定义 UILabel 在 Interface Builder 中未正确显示
【发布时间】:2021-02-16 15:48:18
【问题描述】:

我有一个基于 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 类:

当我删除自定义类标签的名称时,它会正确显示。

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

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

【问题讨论】:

  • 我认为您必须在自定义类中添加 init 方法。
  • 我觉得你需要这样称呼:[super drawRect:rect];

标签: ios swift interface-builder uilabel


【解决方案1】:

我认为你需要这样称呼:

[超级drawRect:rect];

【讨论】:

    【解决方案2】:

    当你继承 UIView 以外的任何东西时,你应该在你的实现中调用 super.draw(_ ...)。 (https://developer.apple.com/documentation/uikit/uiview/1622529-drawrect)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 2011-07-21
      • 2011-07-21
      • 2016-07-10
      • 1970-01-01
      相关资源
      最近更新 更多