我有一个带有一些标签和图像视图的基本单元。我使用视觉格式语言添加了约束,但在运行时却变得模棱两可。到底是怎么回事?!

[self.constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[_typeLabel]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_typeLabel)]];
[self.constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[_addressLabel]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_addressLabel)]];
[self.constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[_mapImageView]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_mapImageView)]];
[self.constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-11-[_typeLabel]-2-[_addressLabel]-[_mapImageView]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_typeLabel, _addressLabel, _mapImageView)]];


这是我的_autolayoutTrace:

*<UITableViewCellContentView:0x940dc30>
|   *<UILabel:0x943aab0> - AMBIGUOUS LAYOUT
|   *<UILabel:0x940ead0> - AMBIGUOUS LAYOUT
|   *<UIImageView:0x9445c20> - AMBIGUOUS LAYOUT
<_UITableViewCellSeparatorView:0x9446200>


以下是影响前两个UILabel的约束:

(lldb) po [0x943aab0 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0x975fee0>(
<NSLayoutConstraint:0x940eca0 H:|-(15)-[UILabel:0x943aab0]   (Names:'|':UITableViewCellContentView:0x940dc30 )>,
<NSLayoutConstraint:0x940ecf0 H:[UILabel:0x943aab0]-(10)-|   (Names:'|':UITableViewCellContentView:0x940dc30 )>,
<NSAutoresizingMaskLayoutConstraint:0x9446a70 h=--& v=--& H:[UITableViewCellContentView:0x940dc30(320)]>
)


(lldb) po [0x943aab0 constraintsAffectingLayoutForAxis:1]
<__NSArrayM 0xaa4af10>(
<NSLayoutConstraint:0x9446030 V:|-(11)-[UILabel:0x943aab0]   (Names:'|':UITableViewCellContentView:0x940dc30 )>,
<NSContentSizeLayoutConstraint:0x943a840 V:[UILabel:0x943aab0(17)] Hug:250 CompressionResistance:750>
)


(lldb) po [0x940ead0 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0x97b4240>(
<NSLayoutConstraint:0x940ed90 H:|-(15)-[UILabel:0x940ead0]   (Names:'|':UITableViewCellContentView:0x940dc30 )>,
<NSLayoutConstraint:0x940ede0 H:[UILabel:0x940ead0]-(10)-|   (Names:'|':UITableViewCellContentView:0x940dc30 )>,
<NSAutoresizingMaskLayoutConstraint:0x9446a70 h=--& v=--& H:[UITableViewCellContentView:0x940dc30(320)]>
)


(lldb) po [0x940ead0 constraintsAffectingLayoutForAxis:1]
<__NSArrayM 0xa985d30>(
<NSLayoutConstraint:0x9446030 V:|-(11)-[UILabel:0x943aab0]   (Names:'|':UITableViewCellContentView:0x940dc30 )>,
<NSLayoutConstraint:0x9446080 V:[UILabel:0x943aab0]-(2)-[UILabel:0x940ead0]>,
<NSContentSizeLayoutConstraint:0x943a840 V:[UILabel:0x943aab0(17)] Hug:250 CompressionResistance:750>,
<NSContentSizeLayoutConstraint:0x9446bb0 V:[UILabel:0x940ead0(33)] Hug:250 CompressionResistance:750>
)

最佳答案

对于歧义布局,您需要将标签的属性设置为contentHuggingcontentCompressionResistance
希望能帮到您
编辑:要了解此属性,您可以按照
Cocoa Autolayout: content hugging vs content compression resistance priority

09-06 11:12