【发布时间】:2013-01-10 23:56:49
【问题描述】:
我使用 [string drawInRect:] 方法,并希望将字符串截断为适合该大小的最大长度。这并不像找出每行有多少个字符那么简单,因为每个字母的宽度都不同。我想找到字符串不再可见的原因是我可以在字符串的末尾添加省略号。
【问题讨论】:
-
标记为重复的问题解释了如何测量 NSString,而不是如何截断它。
-
这是一种方法:
- (NSString *)stringByTruncatingToWidth:(CGFloat)width attributes:(NSDictionary *)textFontAttributes { CGSize size = [self sizeWithAttributes:textFontAttributes]; if (size.width <= width) { return self; } for (int i = 2; i < self.length; i++) { NSString *testString = [NSString stringWithFormat:@"%@…", [self substringToIndex:self.length - i]]; CGSize size = [testString sizeWithAttributes:textFontAttributes]; if (size.width <= width) { return testString; } } return @""; }
标签: iphone ios objective-c nsstring