Skip to content

Instantly share code, notes, and snippets.

@billyohgren
Last active April 20, 2020 13:04
Show Gist options
  • Star 48 You must be signed in to star a gist
  • Fork 23 You must be signed in to fork a gist
  • Save billyohgren/7944887 to your computer and use it in GitHub Desktop.
Save billyohgren/7944887 to your computer and use it in GitHub Desktop.
Calculate the actual size of the content inside a UILabel
#import <UIKit/UIKit.h>
@interface UILabel (ContentSize)
- (CGSize)contentSize;
@end
#import "UILabel+ContentSize.h"
@implementation UILabel (ContentSize)
- (CGSize)contentSize {
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = self.lineBreakMode;
paragraphStyle.alignment = self.textAlignment;
NSDictionary * attributes = @{NSFontAttributeName : self.font,
NSParagraphStyleAttributeName : paragraphStyle};
CGSize contentSize = [self.text boundingRectWithSize:self.frame.size
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil].size;
return contentSize;
}
@juwencheng
Copy link

thxs

@echohuub
Copy link

echohuub commented Oct 8, 2014

That's cool

@syrakozz
Copy link

+1

@sqintian
Copy link

fuck

@ricardosousaDev
Copy link

Legend! Thanks!

@DepthSky
Copy link

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment