Skip to content

Instantly share code, notes, and snippets.

@NikolaiRuhe NikolaiRuhe/NRLabel.m
Last active Nov 27, 2018

Embed
What would you like to do?
A UILabel subclass that adds padding around the text and handles layout properly.
@interface NRLabel : UILabel
@property (nonatomic) UIEdgeInsets textInsets;
@end
@implementation NRLabel
- (void)setTextInsets:(UIEdgeInsets)textInsets
{
_textInsets = textInsets;
[self invalidateIntrinsicContentSize];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
UIEdgeInsets insets = self.textInsets;
CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)
limitedToNumberOfLines:numberOfLines];
rect.origin.x -= insets.left;
rect.origin.y -= insets.top;
rect.size.width += (insets.left + insets.right);
rect.size.height += (insets.top + insets.bottom);
return rect;
}
- (void)drawTextInRect:(CGRect)rect
{
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.textInsets)];
}
@end
@xingheng

This comment has been minimized.

Copy link

commented Jul 25, 2017

How about the text length is 0? For UILabel class, the textRectForBounds returns CGSizeZero when it's empty. It'd better add the following statement when overriding it.

    if (self.text.length > 0) {
        rect.size.width += (insets.left + insets.right);
        rect.size.height += (insets.top + insets.bottom);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.