请问在写autolayout 约束时候怎么优雅的完成控件顶部距离为父视图高度的等比?

比如 我有一个imageView 加在自身的view上。
想让imageView 距离顶部的距离为 view高度的1/4 应该怎么写?

我自己写的:

 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0.25 constant:0]];

我理解的 imageView.top = self.view.height*0.25 + 0 的逻辑感觉没什么问题,但是运行报错。。 求解答。
'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Invalid pairing of layout attributes'

然后我在stackoverflow 上找到答案 是向下面这么写:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:0.25 constant:0]];

运行成功。 但我不能理解
imageView.top = self.view.bottom *0.25 + 0

这里self.view.bottom是多少? view是self.veiw 父视图了~
他的bottom多少呢? 又是相对什么而言得出的数值呢? 理解不能 求大神解答!

阅读 8.5k
2 个回答

如果用storyboard可以这样:
1.把imageview的顶部拖到与superview的bottom齐平。
2.改变Align Center Y的Mutiplier,1改为4,即为superview的1/4处。

你可以这样理解,imageView.top = self.view.bottom*1 就是:

                   |
  self.view.bottom |  
      v            |
------------------(1)
      ^            |
  imageView.top    |
                   |

imageView.top = self.view.bottom*0.25,就是在上面的基础上乘以0.25,就是:

------------ > (self.view.top)
(self.view)
------------ > self.view.bottom * 0.25
     ^
imageView.top

------------ > self.view.bottom * 1
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题