Ellipsis at the end of UITextView

后端 未结 3 2065
无人共我
无人共我 2021-02-09 02:19

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         


        
相关标签:
3条回答
  • 2021-02-09 02:42

    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
    
    0 讨论(0)
  • 2021-02-09 02:57

    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 讨论(0)
  • 2021-02-09 02:59

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

    0 讨论(0)
提交回复
热议问题