如何调整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.
我已设置行打破Word Wrap并尝试使用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;