本文介绍了如何调整 UIButton 的大小以适应文本而不使其比屏幕更宽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我有一个 UIButton,我想调整它的大小以适应其中的任何文本.它的宽度设置为 280,但文本应换行到下一行并根据需要扩展按钮的高度.
I have a UIButton that I want to resize to fit whatever text is inside it. It has a set width of 280, but the text should wrap to the next line(s) and extend the height of the button as needed.
我已将换行设置为自动换行并尝试了 sizeToFit,但这只会使按钮变宽,而不是垂直.
I've set line breaks to Word Wrap and tried sizeToFit but that only makes the button go wider, not vertical.
推荐答案
我设法让它在 UIButton 的类别中工作:
I managed to get it working in a category of UIButton:
@interface UIButton (ExpandsVertically)
- (CGSize)sizeThatFits:(CGSize)size;
@end
@implementation UIButton (Expandable)
- (CGSize)sizeThatFits:(CGSize)size {
// for the width, I subtract 24 for the border
// for the height, I use a large value that will be reduced when the size is returned from sizeWithFont
CGSize tempSize = CGSizeMake(size.width - 24, 1000);
CGSize stringSize = [self.titleLabel.text
sizeWithFont:self.titleLabel.font
constrainedToSize:tempSize
lineBreakMode:UILineBreakModeWordWrap];
return CGSizeMake(size.width - 24, stringSize.height);
}
@end
如果有人使用它,请确保设置:
If anyone uses this make sure to set:
myButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
这篇关于如何调整 UIButton 的大小以适应文本而不使其比屏幕更宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)