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];
The result is shown below:
I want the button to size to its content. How can I do this?
I've tried
[self.button sizeToFit];
and I've tried setting the content hugging and compression resistance autolayout constraints priorities to required.
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.
I'm running on Xcode 6 and iOS 8 on the iPhone 6 Simulator.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…