Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

autolayout

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?

like image 847
circuitlego Avatar asked Jul 04 '13 13:07

circuitlego


People also ask

What specifies how child views are positioned?

Android RelativeLayout enables you to specify how child views are positioned relative to each other. The position of each view can be specified as relative to sibling elements or relative to the parent.

How do I create a relative layout?

Navigate to the app > res > layout > activity_main. xml and add the below code to that file. Below is the code for the activity_main. xml file.

Which XML attribute can be used to put a view in front of other views?

bringToFront()” method will let you a perfect indicator view :) Also, there is another option to use a parent-children relationship views.


1 Answers

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];
like image 73
Michael McGuire Avatar answered Oct 07 '22 19:10

Michael McGuire