我有一个UIButton,我想调整它的大小以适应其中的任何文本。它的宽度设置为280,但文本应该换行到下一行,并根据需要扩展按钮的高度。
我已经将换行符设置为Word Wrap,并尝试了sizeToFit,但这只会使按钮变宽,而不是垂直。
发布于 2011-02-12 20:15:43
我设法让它在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如果有人使用它,请确保设置:
myButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;发布于 2012-08-20 22:17:16
确保按键上的文本是这样设置的:
[myButton setTitle:@"my title" forState:UIControlStateNormal];..。而且[myButton sizeToFit]应该像一个护身符一样工作。
发布于 2013-01-21 17:26:10
[button sizeToFit]不适用于我,但我找到了一种单独使用IB (Xcode4.5)的方法:
UIButtoncontent hugging拖动到1(水平和垂直)compression resistance拖动到1000 (对于两者)UIButton下的D13并将D14更改为250H116对高度执行相同的操作您可以使用D19的D20来控制left/right/top/bottom的填充
https://stackoverflow.com/questions/4960377
复制相似问题