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?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With