How to truncate an NSString based on the graphical width?

六月ゝ 毕业季﹏ 提交于 2019-12-06 01:38:46

问题


In UILabel there's functionality to truncate labels using different truncation techniques (UILineBreakMode). In NSString UIKit Additions there is a similar functionality for drawing strings.

However, I found no way to access the actual truncated string. Is there any other way to get a truncated string based on the (graphical) width for a given font?

I'd like to have a category on NSString with this method:

-(NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

回答1:


One option is trying different sizes by looping until you get the right width. I.e. start with the full string, if that's wider than what you need, replace the last two characters with an ellipsis character. Loop until it's narrow enough.

If you think you'll be working with long strings, you can binary search your way towards the truncation point to make it a bit faster.




回答2:


- (NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode {
    NSMutableString *resultString = [[self mutableCopy] autorelease];
    NSRange range = {resultString.length-1, 1};

    while ([resultString boundingRectWithSize:CGSizeMake(FLT_MAX, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.width > width) {
        // delete the last character
        [resultString deleteCharactersInRange:range];
        range.location--;
        // replace the last but one character with an ellipsis
        [resultString replaceCharactersInRange:range withString:truncateReplacementString];
    }
    return resultString;
}

Note that since iOS 6 this method is not safe to run on background threads anymore.



来源:https://stackoverflow.com/questions/2266396/how-to-truncate-an-nsstring-based-on-the-graphical-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!