我以編程方式將UIButton物件添加到UIScrollView. 我得到的結果是按鈕的高度計算正確,即第二行有一個空間,但文本沒有換行,而是繼續流動,好像按鈕有無限的寬度。我曾經有UITextView物件而不是按鈕,而且效果很好。我只是無法將按鈕設定為與文本視圖相同的布局。
這是一個代碼片段:
UIButton* sButton = [[UIButton alloc] initWithFrame:CGRectMake(0, yPos, sWidth - 5, height)];
sText = [[NSMutableString alloc] initWithString:@"quite a long string that does not fit in one line, no chance"];
sButton.titleLabel.font = font;
sButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[sButton setLineBreakMode:NSLineBreakByWordWrapping];
[sButton.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
[sButton setTitle:sText forState:UIControlStateNormal];
[sButton sizeToFit];
這是我得到的結果:
如何使按鈕文本換行?
uj5u.com熱心網友回復:
這是我發現的唯一可行的解??決方案:https ://stackoverflow.com/a/4978003/963022
我最終創建了一個自定義按鈕實作并覆寫:
- (CGSize)sizeThatFits:(CGSize)size {
int diff = 0;
// for the width, subtract DIFF for the border
// for the height, use a large value that will be reduced when the size is returned from sizeWithFont
CGSize tempSize = CGSizeMake(size.width - diff, 1000);
CGSize stringSize = [self.titleLabel.text
sizeWithFont:self.titleLabel.font
constrainedToSize:tempSize
lineBreakMode:UILineBreakModeWordWrap];
return CGSizeMake(size.width - diff, stringSize.height);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/513012.html
標籤:IOS目标-c按钮
上一篇:ReactNative[macOS]中未顯示橋接本機模塊
下一篇:ReactNativeiOSsendEventWithName導致“RCTCallableJSModules未設定”
