Skip to content

Instantly share code, notes, and snippets.

@NikolaiRuhe
Last active November 27, 2018 07:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikolaiRuhe/26498fb2f7d427cd9b62a858af9ead64 to your computer and use it in GitHub Desktop.
Save NikolaiRuhe/26498fb2f7d427cd9b62a858af9ead64 to your computer and use it in GitHub Desktop.
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
Copy link

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