具有尾部截断的UIButton多行文本

Joh*_*ohn 8 multiline uibutton ipad

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

[myUIButton.titleLabel setLineBreakMode:UILineBreakModeWordWrap];
[myUIButton setTitle:myTitle forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

但是,这会导致按钮标题占用许多行.我试过限制使用的行数

[myUIButton.titleLabel setNumberOfLines:2];
Run Code Online (Sandbox Code Playgroud)

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

有没有办法限制在UIButton标题上包含2行的行,然后将尾部截断为"..."?

小智 9

通过设置lineBreakMode之前numberOfLines可以实现所需的结果...这是因为lineBreakMode似乎取消了numberOfLines设置因此我们按此顺序进行.

Objective-C的:

[button.titleLabel setLineBreakMode: UILineBreakModeTailTruncation];
[button.titleLabel setNumberOfLines:2];
[button setTitle:myTitle forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

Swift 3:从Xcode 6及以上UILineBreakMode代替NSLineBreakMode

button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
button.titleLabel?.numberOfLines = 2
button.setTitle(myTitle, for: UIControlState.normal)
Run Code Online (Sandbox Code Playgroud)


小智 3

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

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

// 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];
Run Code Online (Sandbox Code Playgroud)

以及 truncateString 方法:

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

    return  stringToTruncate;
}
Run Code Online (Sandbox Code Playgroud)

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