I use following function to space a dynamic number of views across a View (with autolayout):
-(NSArray*)spaceViews:(NSArray *)views onAxis:(UILayoutConstraintAxis)axis
{
NSAssert([views count] > 1,@"Can only distribute 2 or more views");
NSLayoutAttribute attributeForView;
NSLayoutAttribute attributeToPin;
switch (axis) {
case UILayoutConstraintAxisHorizontal:
attributeForView = NSLayoutAttributeCenterX;
attributeToPin = NSLayoutAttributeRight;
break;
case UILayoutConstraintAxisVertical:
attributeForView = NSLayoutAttributeCenterY;
attributeToPin = NSLayoutAttributeBottom;
break;
default:
return @[];
}
CGFloat fractionPerView = 1.0 / (CGFloat)([views count] + 1);
NSMutableArray *constraints = [NSMutableArray array];
[views enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL *stop)
{
CGFloat multiplier = fractionPerView * (idx + 1.0);
[constraints addObject:[NSLayoutConstraint constraintWithItem:view
attribute:attributeForView
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:attributeToPin
multiplier:multiplier
constant:0.0]];
}];
[self addConstraints:constraints];
return [constraints copy];
}
(The function is from UIView-Autolayout)
The problem is that it has margins. How could this method be changed in order to evenly space the views without margins?
UPDATE
It seems that the method is not working correctly after all, the margins on the outer items are much higher than at the rest.
As an example I changed the code for the left arm to:
self.leftArm = [UIView autoLayoutView];
self.leftArm.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.leftArm];
[self.leftArm pinAttribute:NSLayoutAttributeRight toAttribute:NSLayoutAttributeLeft ofItem:self.body withConstant:-10.0];
[self.leftArm pinAttribute:NSLayoutAttributeTop toSameAttributeOfItem:self.body withConstant:10.0];
[self.leftArm constrainToSize:CGSizeMake(20.0, 200.0)];
Now the robot looks like this:
Note that at the left arm the views are NOT evenly distributed, the margin on top and at the bottom are much higher. I can reproduce the same behavior horizontally and with less items.
I have successfully removed the margins by aligning the outer views with the sides of the superview and aligning the rest within the space between. But now, due to this problem, I always have bigger spaces between the outer views and the views next to them as between the rest.
Does anyone know how to correct this?
UPDATE 2
I have created a fork and added my function to it, I also extended the robot example so you can see what I mean.
Please take a look.