NSLayoutAttributeWidth 和 NSLayoutAttributeLeft + NSLayoutAttributeRight 的区别

Difference between NSLayoutAttributeWidth and NSLayoutAttributeLeft + NSLayoutAttributeRight

如果我有 2 个视图 view1 和 view2。假设 view1 的宽度已在别处设置。我想让 view2 和 view1 的宽度相同

我可以为 view2 创建一个 LayoutConstraintNSLayoutAttributeWidth,将它与 view1 相关联,这应该使 view2 的宽度与 view1 的宽度相同。

或者我可以为 view2 创建两个 LayoutConstraintsNSLayoutAttributeLeft 中的一个与 view1 的左侧相关,NSLayoutAttributeRight 中的第二个与 view1 的右侧相关。它们的左右边缘相同,这不也使 view2 与 view1 的宽度相同吗?

这些匹配宽度的方法是否同样有效?

答案是某种程度上"YES",取决于您的要求。

请记住,有约束条件

NSLayoutAttributeLeft 
NSLayoutAttributeRight 

如果您的 view1 水平移动,view2 也会移动,仍然保持相同的宽度。

如有限制

NSLayoutAttributeWidth 

第一个view1的横向移动不会引起[=13​​=]的移动。