开发者

Ellipsis at the end of UITextView

If I have multi-line non-scrollable UITextView whose text is longer than can fit in the visible area, then the text just cuts off like so:

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

Ho开发者_JS百科w would I get the text to show with an ellipsis where the text cut-off is, like so

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

Other controls like labels and buttons have this ability.


Why not use a UILabel setting numberOfLines to something appropriate and getting that functionality for free?


The UITextView is designed to scroll when the string is larger than what the view can show. Make sure that you have set the anchoring and autoresize attributes correctly in code or your xib.

Here is an example from a blog post about how to implement your own ellipsis.

@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


Someone just showed me that it's actually really easy to do this with UITextView on iOS 7 and up:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜