提问人:Eir 提问时间:9/25/2022 最后编辑:Eir 更新时间:9/28/2022 访问量:258
UIButton 宽度或换行模式问题
UIButton width or line break mode problem
问:
我正在以编程方式将对象添加到 .我得到的结果是按钮的高度计算正确,即第二行有一个空格,但文本没有换行,而是继续流动,就好像按钮具有无限宽度一样。我曾经用对象代替按钮,而且效果很好。我只是无法将按钮设置为与文本视图相同的布局方式。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];
如何使按钮文本换行?
答:
0赞
Eir
9/28/2022
#1
这是我找到的唯一有效的解决方案: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);
}
评论
UIButtonConfiguration
UIButton
sizeToFit
sizeToFit
sizeToFit
UITextView
UIButton
sizeToFit
sizeToFit