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

时间:2011-02-10 17:16:17

标签: iphone uibutton

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

我已经为Word Wrap设置了换行符并尝试了sizeToFit,但这只会让按钮更宽,而不是垂直。

5 个答案:

答案 0 :(得分:33)

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

[myButton setTitle:@"my title" forState:UIControlStateNormal];

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

答案 1 :(得分:7)

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

  1. 点击UIButton
  2. 在尺寸检查器中
  3. content hugging拖动到1(水平和垂直)
  4. compression resistance拖至1000(两者都是)
  5. 在UIButton的constraints下点击Width并将priority更改为250
  6. 为Height做同样的事情
  7. 您可以使用UIButton的{​​{1}}来控制左/右/上/下的填充

答案 2 :(得分:2)

您可能需要查看UIKit Additions to NSString documentation,其中包括限制为特定宽度或框大小的字体测量方法。

当您设置按钮的标题时,您可以使用 sizeWithFont:forWidth:lineBreakMode:方法测量字符串,并根据返回的大小更新按钮的框架(可能允许一些在边缘附近填充。)

抱歉,我没有具体的例子。

答案 3 :(得分:2)

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

答案 4 :(得分:0)

我一直面临着类似的问题,我的按钮宽度有限,并希望它们垂直增长,具体取决于我给他们的文字数量。 我最终得到了一个简单的解决方案,基于我在Apple文档中学到的内容(https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ImplementingView/ImplementingView.html

我已经将[{1}}子类化并覆盖了两个函数:

UIButton

这里基本上发生的是按钮使其内在大小无效(仅当边界集实际上是新的 - 这是为了防止无限循环),并且当系统要求内在内容大小时,我重新计算基于在按钮的宽度上。额外的20px高度用于填充。 我已经尝试了很多其他方法,但由于我的布局都是基于AutoLayout,我想要的东西是我不必在设备旋转时更新。这很简单。

祝你好运! ž。

相关问题