如何截断Objective-C中的字符串,然后在末尾添加省略号?
答案 0 :(得分:25)
NSString *origString = @"A very long string blah blah blah";
const int clipLength = 18;
if([origString length]>clipLength)
{
origString = [NSString stringWithFormat:@"%@...",[origString substringToIndex:clipLength]];
}
答案 1 :(得分:11)
使用其中一种NSString
方法截断,可能是最后一种:
– substringFromIndex:
– substringWithRange:
– substringToIndex:
然后使用NSString
方法
– stringByAppendingString:
添加@"..."
或任何您喜欢的ellopsis。
例如:
NSString *newString = [[string substringToIndex:12] stringByAppendingString:@"..."];
为了您的阅读乐趣,我推荐NSString
Class Reference。
答案 2 :(得分:9)
如果您希望截断并将省略号添加到最大为特定宽度的字符串,则此处是一个考虑字体和大小的实现:
+ (NSString *)stringByTruncatingString: (NSString *)string toWidth: (CGFloat)width withFont: (UIFont *)font
{
#define ellipsis @"..."
NSMutableString *truncatedString = [string mutableCopy];
if ([string sizeWithAttributes: @{NSFontAttributeName: font}].width > width) {
width -= [ellipsis sizeWithAttributes: @{NSFontAttributeName: font}].width;
NSRange range = {truncatedString.length - 1, 1};
while ([truncatedString sizeWithAttributes: @{NSFontAttributeName: font}].width > width) {
[truncatedString deleteCharactersInRange:range];
range.location--;
}
[truncatedString replaceCharactersInRange:range withString:ellipsis];
}
return truncatedString;
}
答案 3 :(得分:6)
这样做不需要代码。 最简单的方法,
for drawRect
- (void)drawRect:(NSRect)dirtyRect{
NSString *theText = @"bla blah bla bhla bla bla";
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByTruncatingTail];
[theText drawInRect:dirtyRect withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:style, NSParagraphStyleAttributeName,nil]];
}
听到我使用dirtyRect
表示String的绘图区域,您可以根据需要更改它。
NSTextField *_warningTF = [[NSTextField alloc]init];
[_warningTF setStringValue:@"sfdsf sdfdsfdsfdsfdsfdsfdsf 1234566789123456789sfdsf dsf dsfdsf"];
[_warningTF.cell setLineBreakMode:NSLineBreakByTruncatingTail];
答案 4 :(得分:5)
我编写了一个简单的类别,用文字:
截断NSString
@interface NSString (TFDString)
- (NSString *)truncateByWordWithLimit:(NSInteger)limit;
@end
@implementation NSString (TFDString)
- (NSString *)truncateByWordWithLimit:(NSInteger)limit {
NSRange r = NSMakeRange(0, self.length);
while (r.length > limit) {
NSRange r0 = [self rangeOfString:@" " options:NSBackwardsSearch range:r];
if (!r0.length) break;
r = NSMakeRange(0, r0.location);
}
if (r.length == self.length) return self;
return [[self substringWithRange:r] stringByAppendingString:@"..."];
}
@end
<强>用法:强>
NSString *xx = @"This string is too long, somebody just need to take and truncate it, but by word, please.";
xx = [xx truncateByWordWithLimit:50];
结果:
This string is too long, somebody just need to...
希望它对某人有帮助。
答案 5 :(得分:0)
drawWithRect:options:attributes:context方法有帮助。你可以试试这个:
[_ text drawWithRect:_textRect options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine 属性:attributes context:nil];