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

 烟灰TT 发布于 2022-11-01 22:42

比如 我有一个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多少呢? 又是相对什么而言得出的数值呢? 理解不能 求大神解答!

2 个回答
  • 你可以这样理解,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
    
    2022-11-03 10:11 回答
  • 如果用storyboard可以这样:
    1.把imageview的顶部拖到与superview的bottom齐平。
    2.改变Align Center Y的Mutiplier,1改为4,即为superview的1/4处。

    2022-11-03 10:17 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有