简体   繁体   中英

How do I trim an NSString at line x?

This should be a somewhat simple question. I'm trying to trim an NSString to whatever text falls within 150px max height, and then append "Continue Reading" to the end of that trimmed text.. So say we have the following.

a
b
c
d
e
f
g
h
i
j
k
l
m

And we have a font of say, 13... we calculate the total text height and see that it's more than 150px tall at 13px font. My question is, how do I cut the portion of the string that exceeds those 150px?

you could use

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode

(on iOS7 better use boundingRectWithSize:options:attributes:context: )

Keep adding one line to the string while (size.height<150.0f) .

EDIT : This example could work: (Note: If you do not use ARC, trimmedStr should be autoreleased!)

- (NSString*) stringByTrimmingString:(NSString*)str forSize:(CGSize)maxSize withFont:(UIFont*)font
{
    NSMutableString* trimmedStr = [NSMutableString new];
    for (NSString* line in [str componentsSeparatedByString:@"\n"]) {

        NSString *testStr = [trimmedStr stringByAppendingFormat:@"%@\n",line];

        CGSize sz = [testStr sizeWithFont:font forWidth:maxSize.width lineBreakMode:NSLineBreakByWordWrapping];
        if (sz.height > maxSize.height) {
                return [trimmedStr copy];
        }
        [trimmedStr appendFormat:@"%@\n",line];
    }
    return [trimmedStr copy];
}

I do something really rather stupid (brute force) to get this accomplished in my app. I manually create new line characters and indents in a UILabel. To do this I find the first space in the text (to get the end of the first word), check if that is beyond my bounds. If not I move to the second space and check that.

To do something a little more intelligent for you I would split your string in half then see if that half exceeds your bounds. If it does then go to 1/4, if not then go to 3/4 and check that. Then once you find the character that makes you exceed your limit then do a backward search for a space (to find the last word that fits) and truncate your string there. This may seem like difficult code, but it's just like a binary search algorythm, but through your string.

You can simply use

-(CGSize)sizeWithFont:(UIFont*)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode;

because it takes into account all \\n characters and calculates correct CGSize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM