【问题标题】:UIButton multi-line text with tail truncation带有尾部截断的 UIButton 多行文本
【发布时间】:2011-03-22 20:25:02
【问题描述】:

我发现了类似的问题,询问如何在 UIButton 上设置多行文本,解决方案是设置

[myUIButton.titleLabel setLineBreakMode:UILineBreakModeWordWrap];
[myUIButton setTitle:myTitle forState:UIControlStateNormal];

但是,这会导致按钮标题占用很多行。我尝试使用

来限制行数
[myUIButton.titleLabel setNumberOfLines:2];

但这对结果行数没有任何影响。

有没有办法将 UIButton 标题上的 word 换行限制为 2 行,然后用“...”截断尾部?

【问题讨论】:

    标签: uibutton ipad multiline


    【解决方案1】:

    通过在numberOfLines 之前设置lineBreakMode,可以达到您想要的结果…… 这是因为lineBreakMode 似乎取消了numberOfLines 设置,因此我们按此顺序进行。

    目标-C:

    [button.titleLabel setLineBreakMode: UILineBreakModeTailTruncation];
    [button.titleLabel setNumberOfLines:2];
    [button setTitle:myTitle forState:UIControlStateNormal];
    

    斯威夫特 3: 从 Xcode 6 及更高版本开始,UILineBreakModeNSLineBreakMode 替换

    button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
    button.titleLabel?.numberOfLines = 2
    button.setTitle(myTitle, for: UIControlState.normal)
    

    【讨论】:

      【解决方案2】:

      我知道自从第一次提出这个问题以来已经有一段时间了,但我遇到了同样的问题,在考虑了发布的答案后,最终得到了一个简单但实​​用的解决方案 here.

      对我有用的解决方案如下:

      // Set the line break mode to word wrap so it won't truncate automatically
      [button.titleLabel setLineBreakMode: UILineBreakModeWordWrap];
      
      // Call a method that truncates the string I want to use
      [button setTitle:[self truncateString:myButtonText] forState:UIControlStateNormal];
      

      还有 truncateString 方法:

      - (NSString *)truncateString:(NSString *)stringToTruncate
      {
          if ([stringToTruncate length] > 50)
              stringToTruncate = [[stringToTruncate substringToIndex:50] stringByAppendingString:@"..."];
      
          return  stringToTruncate;
      }
      

      所以基本上我计算了适用于我的按钮的字符数,然后强制任何比这更长的字符串在末尾添加“...”。我知道这不是理想的解决方案,但我想它对我们中的一些人有用,我希望它有所帮助。

      【讨论】:

        【解决方案3】:
        [button.titleLabel setNumberOfLines:2];
        [button.titleLabel setLineBreakMode: UILineBreakModeTailTruncation];
        [button setTitle:myTitle forState:UIControlStateNormal];
        

        它为我做到了! :D 干杯!!

        【讨论】:

        • setLineBreakMode 调用似乎取消了 setNumberOfLines 调用。它会截断文本,但不会将行数设置为 2。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-04
        • 2017-04-11
        • 1970-01-01
        • 2012-04-10
        相关资源
        最近更新 更多