我试图了解使用内在内容大小的动态布局的基本。如图所示,我有两个水平的UILabel,这将是我的默认布局。如何使布局约束这样做
您可以向stackView添加两个标签,如果使用UIScreen.main.bounds.width
的intrinsicContentSize和check的总和减去stackView的左右边距。
if (label1.intrinsicContentSize.width + label2.intrinsicContentSize.width) > (UIScreen.main.bounds.width - 48/* 48 is the left and right margins*/) {
stackView.axis = .vertical
}else {
stackView.axis = .horizontal
}
请记住将标签的numberOfLines设置为0。
我能够使用四个约束出口来达到这个条件。
let firstWidth : CGFloat = (firstLabel?.intrinsicContentSize.width)!
let secondWidth : CGFloat = (secondLabel?.intrinsicContentSize.width)!
if (firstWidth + secondWidth) <= self.view.frame.size.width - 45.0 {
secondLabelLeadingConstraintTofirstLabelLeading?.priority = UILayoutPriority(rawValue: 250)
secondLabelSpacingConstraintTofirstLabel?.priority = UILayoutPriority(rawValue: 1000)
secondLabelTopConstraintTofirstLabelTop?.priority = UILayoutPriority(rawValue: 1000)
secondLabelTopConstraintTofirstLabelBottom?.priority = UILayoutPriority(rawValue: 250)
}
else {
secondLabelLeadingConstraintTofirstLabelLeading?.priority = UILayoutPriority(rawValue: 1000)
secondLabelSpacingConstraintTofirstLabel?.priority = UILayoutPriority(rawValue: 250)
secondLabelTopConstraintTofirstLabelTop?.priority = UILayoutPriority(rawValue: 250)
secondLabelTopConstraintTofirstLabelBottom?.priority = UILayoutPriority(rawValue: 1000)
}