Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 

How 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.

like image 461
cannyboy Avatar asked Aug 17 '11 21:08

cannyboy


3 Answers

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

like image 150
Paul.s Avatar answered Sep 25 '22 05:09

Paul.s


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
like image 39
Joe Avatar answered Sep 23 '22 05:09

Joe


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;
like image 38
jasongregori Avatar answered Sep 24 '22 05:09

jasongregori