kkazakov
kkazakov

Reputation: 458

Custom UILabel not displaying properly in Interface Builder

I have a custom UILabel based class, that does not display properly in the storyboard.

All it displays is a blank label. It happens with both XCode 6 and 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

    }
}
}

That's the custom UILabel class in IB:

This is how it looks

When I delete the name of the custom class label, it displays properly.

But it should look like this

When I add it again, it does not disappear. However, the next time it's white again.

When you run the project, it's perfect. I suppose XCode is not rendering it properly, but cannot tell why.

Upvotes: 1

Views: 984

Answers (2)

EvenBoy
EvenBoy

Reputation: 395

When you subclass any other than UIView, you SHOULD CALL super.draw( _ ...) in your implementation. (https://developer.apple.com/documentation/uikit/uiview/1622529-drawrect)

Upvotes: 1

Waqar Ahmed
Waqar Ahmed

Reputation: 150

I think you need to call this:

[super drawRect:rect];

Upvotes: 1

Related Questions