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

时间:2011-03-22 20:25:02

标签: uibutton ipad multiline

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

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

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

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

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

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

3 个答案:

答案 0 :(得分:8)

通过在lineBreakMode之前设置numberOfLines,您可以实现所需的结果...... 这是因为lineBreakMode似乎取消了numberOfLines集,因此我们按此顺序执行此操作。

目标-C:

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

斯威夫特3: 从Xcode 6及以上UILineBreakMode替换为NSLineBreakMode

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

答案 1 :(得分:3)

我知道问题是第一次问到这一段时间已经有一段时间了,但我遇到了同样的问题,并在考虑了发布的答案之后,尝试了一个简单但功能性的解决方案 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;
}

所以基本上我计算了对我的按钮起作用的字符数,然后强制任何比这更长的字符串最后都有'...'。我知道它不是理想的解决方案,但我想它可以为我们中的一些人工作,我希望它有所帮助。

答案 2 :(得分:1)

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

它适合我! :d 欢呼声!!

相关问题