How to position a child view relative to containing view size?

北慕城南 提交于 2019-12-22 02:31:10

问题


I want to be able to position my child view 25% the size of the super view from the top.

NSLayoutConstraint *topPositionConstraint = [NSLayoutConstraint  constraintWithItem:_containerView 
                                                                          attribute:NSLayoutAttributeTop 
                                                                          relatedBy:NSLayoutRelationEqual 
                                                                             toItem:_childView 
                                                                          attribute:NSLayoutAttributeHeight 
                                                                         multiplier:0.25f 
                                                                           constant:0.0f];

However, right now I'm getting the following exception:

'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Invalid pairing of layout attributes'

Why does the error occur and how can I achieve what I want?


回答1:


You can't use top and height in the same constraint. Although it makes sense to say it the system doesn't like it.

What you could do instead is something like...

NSLayoutConstraint *topPositionConstraint =
    [NSLayoutConstraint  constraintWithItem:_childView
                                  attribute:NSLayoutAttributeTop 
                                  relatedBy:NSLayoutRelationEqual 
                                     toItem:_containerView
                                  attribute:NSLayoutAttributeTop 
                                 multiplier:1.0 
                                   constant:_containerView.frame.size.height * 0.25];



回答2:


Instead of using the frame as in the accepted answer, you can move the percentage to the multiplier if you use the bottom instead of height. I'm using this technique for percentage based positioning of child views. It is also nice because the frame of your container view may not be set when you're creating the constraint:

NSLayoutConstraint *topPositionConstraint =
    [NSLayoutConstraint  constraintWithItem:_childView
                              attribute:NSLayoutAttributeTop 
                              relatedBy:NSLayoutRelationEqual 
                                 toItem:_containerView
                              attribute:NSLayoutAttributeBottom 
                             multiplier:0.25 
                               constant:0];


来源:https://stackoverflow.com/questions/17471240/how-to-position-a-child-view-relative-to-containing-view-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!