ios - 如何根据图形宽度截断 NSString?

标签 ios iphone objective-c cocoa-touch nsstring

在 UILabel 中,有使用不同截断技术 (UILineBreakMode) 截断标签的功能。在 NSString UIKit Additions 中,有一个类似的绘制字符串的功能。

但是,我发现无法访问实际截断的字符串。有没有其他方法可以根据给定字体的(图形)宽度获取截断的字符串?

我想用这个方法在 NSString 上创建一个类别:

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

最佳答案

- (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;
}

请注意,从 iOS 6 开始,此方法在后台线程上运行不再安全。

关于ios - 如何根据图形宽度截断 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2266396/

相关文章:

iphone - Grand Central Dispatch 异步与同步

ios - 有什么方法可以使用 NSURL 访问 iCloud 照片库设置吗?

ios - 使用 Facebook 登录并获取适用于 iOS 7 的电子邮件和用户信息

iOS 联系人框架 : How to fetch contacts by phone number

ios - undefined symbol “_OBJC_CLASS_$_CkoFtp2”与chilikat的链接错误

iphone - 如何创建全局导航堆栈?

iphone - 获取永久 ID 后,核心数据无法为对象完成故障

iphone - 检查应用程序文件夹中是否存在文件

ios - 体系结构 i386 的 undefined symbol 和未找到体系结构 i386 的符号

iphone - UITableViewController 拉动以使用卡住的 header 进行刷新