Skip to content

Instantly share code, notes, and snippets.

@Galeas
Last active April 22, 2016 18:57
Show Gist options
  • Save Galeas/7430979 to your computer and use it in GitHub Desktop.
Save Galeas/7430979 to your computer and use it in GitHub Desktop.
iOS 6 / iOS 7 universal NSString size calculation.
NSString *str = <#some string#>;
CGSize size;
CGSize maxSize = CGSizeMake(<#width#>, <#height#>);
UIFont *font = <#font#>;
if ([str respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineBreakMode:<#Line break mode#>];
[style setAlignment:<#String alignment#>];
NSDictionary *attributes = @{ NSFontAttributeName:font,
NSParagraphStyleAttributeName:style
};
size = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}
else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
size = [str sizeWithFont:font constrainedToSize:maxSize lineBreakMode:<#Line break mode#>];
#pragma clang diagnostic pop
}
@gaizhi
Copy link

gaizhi commented Aug 27, 2015

why it can not calculate string like @"你的电脑中毒了,赶紧关机!!!" ? when width is 300, it return 15.05 for height value and in the view the string display to : 你的电脑中毒了,赶紧{\n}关机!!!, there is a unexpect "\n"

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