问题描述
我创建了一个如下所示的视图控制器:
I have created a view controller that looks like this:
我希望两个顶部按钮与整个视图的左/右边缘之间始终有 20 个点.它们也应该始终具有相同的宽度.我已经为所有这些创建了约束,它完全按照我想要的方式工作.问题是垂直约束.按钮应始终位于顶部边缘下方 20 点处.它们应该具有相同的高度.但是,自动布局不考虑左侧标签需要两行才能容纳其所有文本,因此结果如下所示:
I want the two top buttons to always have 20 points between themselves and the left/right edges of the whole view. They should always have the same width too. I have created the constraints for all of this and it works exactly how I want it to. The problem is the vertical constraints. The buttons should always be 20 points beneath the top edge. They should have the same height. However, autolayout doesn't respect that the left label needs two lines to fit all its text, so the result looks like this:
我希望它看起来像第一张图片.我不能为按钮添加恒定的高度限制,因为当应用程序在 iPad 上运行时,只需要一行,然后有额外的空间会很浪费.
I want it to look like in the first picture. I can't add constant height constraints to the buttons because when the app runs on iPad, only one line is needed and it would be wasteful to have extra space then.
在 viewDidLoad 我试过这个:
- (void)viewDidLoad
{
[super viewDidLoad];
self.leftButton.titleLabel.preferredMaxLayoutWidth = (self.view.frame.size.width - 20.0 * 3) / 2.0;
self.rightButton.titleLabel.preferredMaxLayoutWidth = (self.view.frame.size.width - 20.0 * 3) / 2.0;
}
但这并没有改变任何东西.
But that did not change anyhting at all.
问题:如何让自动布局尊重左键需要两行?
推荐答案
我有同样的问题,我希望我的按钮随着它的标题一起增长.我必须将 UIButton 及其 intrinsicContentSize 子类化,以便它返回标签的固有大小.
I had the same problem where I wanted my button to grow along with its title. I had to sublcass the UIButton and its intrinsicContentSize so that it returns the intrinsic size of the label.
- (CGSize)intrinsicContentSize
{
return self.titleLabel.intrinsicContentSize;
}
由于 UILabel 是多行的,它的 intrinsicContentSize 是未知的,你必须设置它的 preferredMaxLayoutWidth 参见objc.io文章
Since the UILabel is multiline, its intrinsicContentSize is unknown and you have to set its preferredMaxLayoutWidth See objc.io article about that
- (void)layoutSubviews
{
[super layoutSubviews];
self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width;
[super layoutSubviews];
}
布局的其余部分应该可以工作.如果您将两个按钮设置为具有相同的高度,则另一个将增长到.完整的按钮如下所示
The rest of the layout should work. If you set your both button having equal heights, the other one will grow to. The complete button looks like this
@implementation TAButton
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
self.titleLabel.numberOfLines = 0;
self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
}
return self;
}
- (CGSize)intrinsicContentSize
{
return self.titleLabel.intrinsicContentSize;
}
- (void)layoutSubviews
{
[super layoutSubviews];
self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width;
[super layoutSubviews];
}
@end
这篇关于多行 UIButton 和自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)