iOS自动布局:将尾随空格设置为等于超视图的宽度

Luc*_*rdi 3 cocoa-touch ios autolayout

我需要使用自动布局在其超视图的右边界外放置一个视图.

我试图通过指定以下NSLayoutConstraint来做到这一点:

NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.downloadView
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.contentView
                                                                  attribute:NSLayoutAttributeWidth
                                                                 multiplier:1.0
                                                                   constant:0.0];
Run Code Online (Sandbox Code Playgroud)

self.downloadView包含的是self.contentView的子视图.通过这样做iOS抱怨有以下异常:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Invalid pairing of layout attributes'
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么我不能配对这两个属性,我怎样才能实现我的目标?

Rob*_*Rob 8

是的,您不能将leading属性设置为与width属性相关contentView.但是,例如,您可以设置downloadView相对于其尾随属性的前导属性superview,即contentView:

NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.downloadView
                                                                  attribute:NSLayoutAttributeLeading
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.contentView
                                                                  attribute:NSLayoutAttributeTrailing
                                                                 multiplier:1.0
                                                                   constant:0.0];
Run Code Online (Sandbox Code Playgroud)

或者您可以定义downloadView要相对于其的主要属性的前导属性contentView,但是然后将其constant设置为某个值,例如视图的宽度.但是,这种技术的问题是,在方向改变时,constant不再适合,你可能不得不调整它.