Thursday, March 13, 2014

Percentage based layouts using (mostly) Xcode IB and Autolayout

The Xcode lnterface Builder (IB) doesn't provide a clear way to handle a percentage based layout - for example, a screen where one view takes up 25% of the width of the screen, and the other view gets the rest.

---------------------------------------------------
|                    |                                              |
|                    |                                              |
|                    |                                              |
|        A         |                       B                     |
|                    |                                              |
|                    |                                              |
|                    |                                              |
---------------------------------------------------

Here's one way to use IB for all but a few lines of code.  (based on ideas from this stackoverflow post.)

For "view B", using Xcode IB, I put constraints on the top, right, bottom, and left
For "view A", using Xcode IB, I put constraints on the top, left, bottom, and then set the width to a fixed size.  I edited the width constraint of "view A", and checked the "placeholder remove at build time" checkbox.

then, in the view controller's viewDidLoad, I added these two lines:


    NSLayoutConstraint *c = [NSLayoutConstraint constraintWithItem:viewA
                           attribute:NSLayoutAttributeWidth
                           relatedBy:NSLayoutRelationEqual
                            toItem:viewA.superview
                            attribute:NSLayoutAttributeWidth
                            multiplier:.25
                            constant:(CGFloat)0];
   

    [viewA.superview addConstraint:c];



This just makes viewA 25% of the size of it's superview.  Since viewB is tied to viewA's width, it also adjusts properly without having to specify extra constraints for it.

1 comment: