【问题标题】:Ellipsis at the end of UITextViewUITextView 末尾的省略号
【发布时间】:2011-08-17 21:17:07
【问题描述】:

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

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

我如何让文本在文本截断的地方用省略号显示,就像这样

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

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

【问题讨论】:

    标签: iphone objective-c ios uitextview


    【解决方案1】:

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

    【讨论】:

    • 可能是因为:如果您需要一定区域的空间填充椭圆形的文本,如果您可以计算将使用的确切行数,则该文本仅适用于 UILabel,这很难通过改变屏幕尺寸。行太少,最后会有空白,太多,省略号根本不会显示,因为它会在屏幕外。
    【解决方案2】:

    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
    

    【讨论】:

    • 我会推荐一个 UILabel 但如果你需要编辑查看这篇文章iphonedevelopertips.com/cocoa/…
    • 使用 UITextView,不要忘记考虑控件在文本周围添加的 8px 边框。这可能会在确定宽度时导致问题。
    【解决方案3】:

    有人刚刚向我展示了在 iOS 7 及更高版本上使用 UITextView 执行此操作实际上非常容易:

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

    【讨论】:

      猜你喜欢
      • 2020-04-24
      • 2016-05-27
      • 2017-06-23
      • 1970-01-01
      • 2015-10-16
      • 2015-02-06
      • 2018-11-30
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多