Created
June 9, 2011 16:45
-
-
Save danielphillips/1017149 to your computer and use it in GitHub Desktop.
Get number of lines required for a UILabel
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 UILabel (GetLines) | |
- (NSArray*) lines; | |
@end |
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
#import "UILabel+GetLines.h" | |
@implementation UILabel (GetLines) | |
- (NSArray*) lines | |
{ | |
if ( self.lineBreakMode != UILineBreakModeWordWrap ) | |
{ | |
return nil; | |
} | |
NSMutableArray* lines = [NSMutableArray arrayWithCapacity:10]; | |
NSCharacterSet* wordSeparators = [NSCharacterSet whitespaceAndNewlineCharacterSet]; | |
NSString* currentLine = self.text; | |
int textLength = [self.text length]; | |
NSRange rCurrentLine = NSMakeRange(0, textLength); | |
NSRange rWhitespace = NSMakeRange(0,0); | |
NSRange rRemainingText = NSMakeRange(0, textLength); | |
BOOL done = NO; | |
while ( !done ) | |
{ | |
// determine the next whitespace word separator position | |
rWhitespace.location = rWhitespace.location + rWhitespace.length; | |
rWhitespace.length = textLength - rWhitespace.location; | |
rWhitespace = [self.text rangeOfCharacterFromSet: wordSeparators options: NSCaseInsensitiveSearch range: rWhitespace]; | |
if ( rWhitespace.location == NSNotFound ) | |
{ | |
rWhitespace.location = textLength; | |
done = YES; | |
} | |
NSRange rTest = NSMakeRange(rRemainingText.location, rWhitespace.location-rRemainingText.location); | |
NSString* textTest = [self.text substringWithRange: rTest]; | |
CGSize sizeTest = [textTest sizeWithFont: self.font forWidth: 1024.0 lineBreakMode: UILineBreakModeWordWrap]; | |
if ( sizeTest.width > self.bounds.size.width ) | |
{ | |
[lines addObject: [currentLine stringByTrimmingCharactersInSet:wordSeparators]]; | |
rRemainingText.location = rCurrentLine.location + rCurrentLine.length; | |
rRemainingText.length = textLength-rRemainingText.location; | |
continue; | |
} | |
rCurrentLine = rTest; | |
currentLine = textTest; | |
} | |
[lines addObject: [currentLine stringByTrimmingCharactersInSet:wordSeparators]]; | |
return lines; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment