如何將多行文本添加到UIButton?

我有如下代碼... 編程

UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds];
buttonLabel.text = @"Long text string";
[targetButton addSubview:buttonLabel];
[targetButton bringSubviewToFront:buttonLabel];

...這個想法是我能夠爲按鈕添加多行文本,可是該文本始終被UIButton的backgroundImage遮蓋。 顯示該按鈕的子視圖的日誌記錄調用代表已添加UILabel,但看不到文本自己。 這是UIButton中的錯誤仍是我作錯了什麼? app


#1樓

對於使用Xcode 4故事板的用戶,能夠單擊按鈕,而後在Attributes Inspector下的Utilities窗格的右側,將看到一個Line Break選項。 選擇自動換行,您應該一切順利。 佈局


#2樓

對於IOS 6: spa

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;

日誌

UILineBreakModeWordWrap and UITextAlignmentCenter

從IOS 6開始不推薦使用。 code


#3樓

有一種更簡單的方法: get

someButton.lineBreakMode = UILineBreakModeWordWrap;

(針對iOS 3及更高版本進行編輯:) string

someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

#4樓

這裏的答案告訴您如何以編程方式實現多行按鈕標題。 it

我只是想補充一下,若是您使用情節提要,則能夠鍵入[Ctrl + Enter]來在按鈕標題字段上強制換行。 方法

高溫超導


#5樓

若是在iOS 6上使用自動佈局,則可能還須要設置preferredMaxLayoutWidth屬性:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
相關文章
相關標籤/搜索