Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the length of NSString that fits a UILabel with fixed size?

I know NSString has methods that determine the frame size for it, using NSString UIKit Additions, sizeWithFont......

How about the other way around? I mean if I have a fixed frame size, how do I know how many characters or words for a NSString that can fit into it?

If I know this, I can cut off the NSString easily.

thanks

like image 866
Jackson Tale Avatar asked Jun 21 '11 08:06

Jackson Tale


2 Answers

Or you just just use the lineBreak property and set it to NSLineBreakByCharWrapping and move on with your life. https://stackoverflow.com/a/29088337/951349

like image 162
smileBot Avatar answered Nov 22 '22 10:11

smileBot


It might not be the most elegant solution, but you could do something like this:

- (NSString *)string:(NSString *)sourceString reducedToWidth:(CGFloat)width withFont:(UIFont *)font {

    if ([sourceString sizeWithFont:font].width <= width)
        return sourceString;

    NSMutableString *string = [NSMutableString string];

    for (NSInteger i = 0; i < [sourceString length]; i++) {

        [string appendString:[sourceString substringWithRange:NSMakeRange(i, 1)]];

        if ([string sizeWithFont:font].width > width) {

            if ([string length] == 1)
                return nil;

            [string deleteCharactersInRange:NSMakeRange(i, 1)];

            break;
        }
    }

    return string;
}

Then call it like this:

NSString *test = @"Hello, World!";
CGFloat width = 40.0;
UIFont *font = [UIFont systemFontOfSize:[UIFont labelFontSize]];

NSString *reducedString = [self string:test reducedToWidth:width withFont:font];

NSLog(@"%@", reducedString);
like image 37
Morten Fast Avatar answered Nov 22 '22 09:11

Morten Fast