如何调整UIButton的大小以适应文本,而不会超出屏幕范围?

Tig*_*ing 17 iphone uibutton

我有一个UIButton,我想调整大小以适应其中的任何文本.它的设置宽度为280,但文本应该换行到下一行,并根据需要扩展按钮的高度.

我已经为Word Wrap设置换行符并尝试使用sizeToFit,但这只会使按钮变宽,而不是垂直.

Ste*_*AIS 35

确保以这种方式设置按钮上的文本:

[myButton setTitle:@"my title" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

...... [myButton sizeToFit]应该像魅力一样工作.

  • 我认为这可能无法在type = custom的按钮上正常工作 (16认同)

mar*_*mor 8

[button sizeToFit] 对我不起作用,但我找到了一种单独使用IB的方法(xcode 4.5):

  1. 点击 UIButton
  2. 在"大小"检查器中拖动content hugging到1(水平和垂直)
  3. 拖到compression resistance1000(两者都有)
  4. 根据UIButton constraints点击Width并更改priority为250
  5. 为高度做同样的事情
  6. 您可以使用UIButton's inset来控制左/右/上/下填充

  • 使用内容插入而不是标题插入对我有用 (2认同)

Tig*_*ing 3

我设法让它在 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)