iOS自动布局:将尾随空间设置为superview的宽度

iOS自动布局:将尾随空间设置为superview的宽度,ios,cocoa-touch,autolayout,Ios,Cocoa Touch,Autolayout,我需要使用自动布局将视图定位在其superview的右边界之外 我试图通过指定以下NSLayoutConstraint来实现这一点: NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.downloadView attribute:NSLayoutAttri

我需要使用自动布局将视图定位在其superview的右边界之外

我试图通过指定以下NSLayoutConstraint来实现这一点:

NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.downloadView
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.contentView
                                                                  attribute:NSLayoutAttributeWidth
                                                                 multiplier:1.0
                                                                   constant:0.0];
self.downloadView保存的是self.contentView的子视图。 这样做会导致以下例外情况:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Invalid pairing of layout attributes'

有人可以解释为什么我不能将这两个属性配对,以及如何实现我的目标?

是的,您不能将前导属性设置为与
contentView的width属性相关。但是,例如,您可以将
下载视图
的前导属性设置为相对于其
超级视图
内容视图
的尾随属性:

NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.downloadView
                                                                  attribute:NSLayoutAttributeLeading
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.contentView
                                                                  attribute:NSLayoutAttributeTrailing
                                                                 multiplier:1.0
                                                                   constant:0.0];

或者,您可以将
下载视图的前导属性定义为相对于
内容视图的前导属性,但随后将
常量设置为某个值,例如视图的宽度。但是,这种技术的问题是,在方向发生变化时,
常量将不再合适,您可能需要调整它

我已经通过将常数设置为视图的宽度来计算出相同的结果。但正如你所说的,如果方向改变了,它就会停止工作。我更喜欢方向更改安全解决方案。@LucaBernardi是的,我概述的第一种方法是方向安全解决方案。