Last active
April 22, 2016 18:57
-
-
Save Galeas/7430979 to your computer and use it in GitHub Desktop.
iOS 6 / iOS 7 universal NSString size calculation.
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"