【发布时间】:2011-02-10 17:16:17
【问题描述】:
我有一个 UIButton,我想调整它的大小以适应其中的任何文本。它的宽度设置为 280,但文本应换行到下一行并根据需要扩展按钮的高度。
我已将换行设置为自动换行并尝试使用 sizeToFit 但这只会使按钮变宽,而不是垂直。
【问题讨论】:
我有一个 UIButton,我想调整它的大小以适应其中的任何文本。它的宽度设置为 280,但文本应换行到下一行并根据需要扩展按钮的高度。
我已将换行设置为自动换行并尝试使用 sizeToFit 但这只会使按钮变宽,而不是垂直。
【问题讨论】:
确保您以这种方式设置按钮上的文本:
[myButton setTitle:@"my title" forState:UIControlStateNormal];
...和[myButton sizeToFit] 应该像魅力一样工作。
【讨论】:
[button sizeToFit] 对我不起作用,但我找到了一种单独使用 IB 的方法(xcode 4.5):
UIButton
content hugging 拖到 1(水平和垂直)compression resistance 拖动到 1000(两者都适用)constraints 下单击 Width 并将 priority 更改为 250UIButton 的inset 来控制左/右/上/下的填充【讨论】:
您可能想查看UIKit Additions to NSString documentation,其中包含限制为特定宽度或框大小的字体测量方法。
当您设置按钮的标题时,您可以使用 sizeWithFont:forWidth:lineBreakMode: 方法测量字符串,并根据返回的大小更新按钮的框架(可能允许一些边缘填充)。
对不起,我没有具体的例子。
【讨论】:
我设法让它在 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;
【讨论】:
我也遇到过类似的问题,我的按钮宽度有限,并希望它们垂直增长,具体取决于我给它们的文本量。 根据我在 Apple 文档 (https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ImplementingView/ImplementingView.html) 中学到的知识,我最终得到了一个简单的解决方案
我继承了UIButton 并覆盖了两个函数:
- (void)setBounds:(CGRect)bounds {
if (!CGRectEqualToRect(bounds, self.bounds)) {
[self invalidateIntrinsicContentSize];
}
[super setBounds:bounds];
}
- (CGSize)intrinsicContentSize {
//
CGSize size;
self.titleLabel.frame = CGRectMake(self.titleLabel.frame.origin.x,
self.titleLabel.frame.origin.y,
self.frame.size.width - self.contentEdgeInsets.left - self.contentEdgeInsets.right - self.titleEdgeInsets.left - self.titleEdgeInsets.right,
0);
size = [self.titleLabel sizeThatFits:self.titleLabel.frame.size];
size = CGSizeMake(size.width, size.height + 20);
return size;
}
这里基本上发生的是按钮使其固有大小无效(仅当边界集实际上是新的 - 这是为了防止无限循环),并且当系统要求固有内容大小时,我重新计算基于在按钮的宽度上。额外的 20px 高度用于填充。 我尝试了许多其他方法,但由于我的布局都是基于 AutoLayout,我想要一些我不必在设备旋转时更新的东西。这很简单。
祝你好运! Z.
【讨论】: