Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto layout visual programming language for an array of views

Let's say I have an array of views, and I want to stack these views in a list. Now, if I know ahead of time how many views there are, I could write a constraint like this:

"V:|-[view0]-[view1]-[view2]-[view_n]"

However, how can I accomplish something like this with a variable number of views in my array?

like image 868
davidm Avatar asked Oct 10 '13 18:10

davidm


2 Answers

You can iterate over the array and build the string (use an NSMutableString). You need to add the views to a dictionary with keys that match the names you use in the format string.

like image 104
Wain Avatar answered Sep 29 '22 20:09

Wain


Check out this awesome category:

https://github.com/jrturton/UIView-Autolayout

It has a spaceViews method that you can call on the container view and will space an array of views evenly along the specified axis.

There's some sample code in the demo project that should cover everything.

Here is how you would space some views evenly over the vertical axis:
This centre 4 views on the x axis and constrain the width to 150 points. The height would then be calculated depending on the height of self.view

#import "UIView+AutoLayout.h"

...

- (void)spaceViews
{
    NSArray *views = @[ [self spacedView], [self spacedView], [self spacedView], [self spacedView] ];

    [self.view spaceViews:views onAxis:UILayoutConstraintAxisVertical withSpacing:10 alignmentOptions:0];
}

- (UIView *)spacedView
{
    //Create an autolayout view
    UIView *view = [UIView autoLayoutView];

    //Set the backgroundColor
    [view setBackgroundColor:[UIColor redColor]];

    //Add the view to the superview
    [self.view addSubview:view];

    //Constrain the width and center on the x axis
    [view constrainToSize:CGSizeMake(150, 0)];
    [view centerInContainerOnAxis:NSLayoutAttributeCenterX];

    //Return the view
    return view;
}
like image 42
liamnichols Avatar answered Sep 29 '22 20:09

liamnichols