我试图了解使用内在内容大小的动态布局的基础。如图所示,我有两个水平的UILabel,这将是我的默认布局。如何使布局约束以便
答案 0 :(得分:1)
您可以向stackView添加两个标签,如果 intrinsicContentSize 的总和,则检查UIScreen.main.bounds.width
减去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。
答案 1 :(得分:0)
我能够使用四个约束出口来实现这个条件。
为L2添加尾随空格,其值为> = someValue,优先级为999
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)
}