Last active
November 27, 2018 07:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.