调整大小以适合其 titleLabel 的 UIButton [英] UIButton that resizes to fit its titleLabel
问题描述
我有一个 UIButton
,我将它添加到故事板中的视图控制器视图中.我添加了居中约束来定位它,并添加前导空间约束来限制其宽度.在代码中我添加:
I have a UIButton
that I add to my view controller's view in a storyboard. I add centering constraints to position it and leading space constraints to limit its width. In code I add:
self.button.titleLabel.numberOfLines = 0;
self.button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.button setTitle:@"A real real real real real real real real long long name." forState:UIControlStateNormal];
self.button.backgroundColor = [UIColor redColor];
self.button.titleLabel.backgroundColor = [UIColor blueColor];
结果如下图:
我希望按钮的大小适合其内容.我该怎么做?
I want the button to size to its content. How can I do this?
我试过了
[self.button sizeToFit];
并且我已经尝试将内容拥抱和抗压缩自动布局约束优先级设置为必需.
and I've tried setting the content hugging and compression resistance autolayout constraints priorities to required.
我还尝试将 contentEdgeInsets
和 titleEdgeInsets
显式设置为 UIEdgeInsetsZero
并调用 invalidateIntrinsicContentSize
.
I've also tried explicitly setting the contentEdgeInsets
and titleEdgeInsets
to UIEdgeInsetsZero
and calling invalidateIntrinsicContentSize
.
我还注意到,如果我在标题字符串中放置换行符,按钮似乎会调整大小以适应其内容.
I've also noticed that if I place newline characters in the title string, the button does seem to resize to fit its content.
我在 iPhone 6 模拟器上运行 Xcode 6 和 iOS 8.
I'm running on Xcode 6 and iOS 8 on the iPhone 6 Simulator.
推荐答案
我已经让这个工作了,但是你必须使用自定义按钮,而不是系统类型.为按钮提供宽度和高度约束,并为高度约束(我的代码中的heightCon)制作一个IBOutlet,以便您可以在代码中对其进行调整.
I've gotten this to work, but you have to use a custom button, not a system type. Give the button both width and height constraints, and make an IBOutlet to the height constraint (heightCon in my code) so you can adjust it in code.
- (void)viewDidLoad {
[super viewDidLoad];
self.button.titleLabel.numberOfLines = 0;
self.button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.button setTitle:@"A real real real real real real real real long long name." forState:UIControlStateNormal];
[self.button addTarget:self action:@selector(doStuff:) forControlEvents:UIControlEventTouchUpInside];
self.button.backgroundColor = [UIColor redColor];
self.button.titleLabel.backgroundColor = [UIColor blueColor];
[self.button layoutIfNeeded]; // need this to update the button's titleLabel's size
self.heightCon.constant = self.button.titleLabel.frame.size.height;
}
编辑后:
我发现您也可以更简单地执行此操作,如果您创建子类并使用此代码,则使用系统按钮,
I found that you can also do this more simply, and with a system button if you make a subclass, and use this code,
@implementation RDButton
-(CGSize)intrinsicContentSize {
return CGSizeMake(self.frame.size.width, self.titleLabel.frame.size.height);
}
当您设置标题时会调用重写的 internalContentSize 方法.在这种情况下,您不应设置高度限制.
The overridden intrinsicContentSize method is called when you set the title. You shouldn't set a height constraint in this case.
这篇关于调整大小以适合其 titleLabel 的 UIButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!