我有一个UIButton,我想调整大小以适应其中的任何文本.它的设置宽度为280,但文本应该换行到下一行,并根据需要扩展按钮的高度.
我已经为Word Wrap设置换行符并尝试使用sizeToFit,但这只会使按钮变宽,而不是垂直.
Ste*_*AIS 35
确保以这种方式设置按钮上的文本:
[myButton setTitle:@"my title" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)
...... [myButton sizeToFit]应该像魅力一样工作.
[button sizeToFit] 对我不起作用,但我找到了一种单独使用IB的方法(xcode 4.5):
UIButtoncontent hugging到1(水平和垂直)compression resistance1000(两者都有)constraints点击Width并更改priority为250UIButton's inset来控制左/右/上/下填充我设法让它在 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
Run Code Online (Sandbox Code Playgroud)
如果有人使用它,请确保设置:
myButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
Run Code Online (Sandbox Code Playgroud)