2011-03-22 60 views
5

我發現,詢問如何對一個UIButton多行文字類似的問題,以及解決方案的UIButton多行文本是設置用尾巴截斷

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

然而,這導致按鈕標題佔用很多線路。我試圖限制使用的行數

[myUIButton.titleLabel setNumberOfLines:2]; 

但是這對結果行數沒有任何影響。

有沒有辦法將UIButton標題中的行字限制爲2行,然後將尾部截斷爲「...」?

回答

2

我知道它已經有一段時間,因爲這個問題是第一次提出,但我遇到了同樣的問題來了,考慮到答案後,用一個簡單而實用的解決方案endend了貼 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; 
} 

所以基本上我計算了可以用於我的按鈕的字符數量,然後強制任何字符串比最後的'...'長。我知道它不是理想的解決方案,但我想它可以爲我們中的一些人工作,我希望它可以幫助。

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

它爲我做到了! :D 歡呼!

+1

取代的setLineBreakMode呼叫似乎抵消setNumberOfLines調用。它會截斷文本,但不會將行數設置爲2。 – rplankenhorn 2013-11-18 19:59:25

3

通過設置lineBreakMode之前numberOfLines你期望的結果,可以實現... 這是因爲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)