问题描述
我有一个UIButton,我添加到我的视图控制器视图故事板。我加定心约束来放置它,并导致空间的限制,以限制它的宽度。在code我补充一下:
I have a UIButton that I add to my view controller 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];
的结果如下所示:
The result is shown below:
我希望按钮的大小对其内容。我怎样才能做到这一点?
I want the button to size to its content. How can I do this?
我试过
[self.button sizeToFit];
和我试过内容拥抱和COM pression电阻自动布局约束优先设置为必需的。
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.
我在X code 6和iOS 8的iphone模拟器6运行。
I'm running on Xcode 6 and iOS 8 on the iphone 6 simulator.
推荐答案
我已经得到这个工作,但你必须使用一个自定义按钮,而不是一个系统类型。将按钮宽度和高度的限制,并作出一个IBOutlet的高度约束(heightCon在我的code),因此您可以在code调整。
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;
}
修改后:
我发现,你也可以做到这一点更简单,并与系统按钮,如果你犯了一个子类,并使用此code,
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);
}
当您设置标题的覆盖intrinsicContentSize方法被调用。你不应该在这种情况下设置一个高度约束。
The overridden intrinsicContentSize method is called when you set the title. You shouldn't set a height constraint in this case.
这篇关于这UIButton的调整大小以适应其titleLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!