在UITextView末尾的省略号

时间:2011-08-17 21:17:08

标签: iphone objective-c ios uitextview

如果我有多行不可滚动的UITextView,其文本长度超出可见区域,那么文本就像这样切断:

Congress shall make no law respecting 
an establishment of religion, or 

如何将文本显示为文本截止的省略号,如此

Congress shall make no law respecting
an establishment of religion, or … 

标签和按钮等其他控件具备此功能。

3 个答案:

答案 0 :(得分:6)

为什么不在适当的情况下使用UILabel设置numberOfLines并免费获得该功能?

答案 1 :(得分:4)

UITextView用于在字符串大于视图可以显示的内容时滚动。确保在代码或xib中正确设置了锚定和自动调整大小属性。

以下是blog post关于如何实现自己的省略号的示例。

@interface NSString (TruncateToWidth)
- (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font;
@end

#import "NSString+TruncateToWidth.h"

#define ellipsis @"…"

@implementation NSString (TruncateToWidth)

- (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font
{
  // Create copy that will be the returned result
  NSMutableString *truncatedString = [[self mutableCopy] autorelease];
  // Make sure string is longer than requested width
  if ([self sizeWithFont:font].width > width)
  {
    // Accommodate for ellipsis we'll tack on the end
    width -= [ellipsis sizeWithFont:font].width;
    // Get range for last character in string
    NSRange range = {truncatedString.length - 1, 1};

    // Loop, deleting characters until string fits within width
    while ([truncatedString sizeWithFont:font].width > width) 
    {
      // Delete character at end
      [truncatedString deleteCharactersInRange:range];
      // Move back another character
      range.location--;
    }

    // Append ellipsis
    [truncatedString replaceCharactersInRange:range withString:ellipsis];
  }

  return truncatedString;
}

@end

答案 2 :(得分:2)

有人刚刚告诉我,使用iOS 7及更高版本的UITextView实际上很容易做到这一点:

UITextView *textView = [UITextView new];
textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;