Tuesday, 17 September 2013

how to horizontally align 3 subviews of a UIView with NSLayoutConstraint visual format

how to horizontally align 3 subviews of a UIView with NSLayoutConstraint
visual format

I have the following setup:
A UIView with size (40,40)
3 subviews of this view, each with frames (0,0,40,40)
Now I'd like for this setup to have the following constraint hold at all
times:
H:|-10-[v1]-10-[v2]-10-[v3]-10-|
Which implies the following desired behavior throughout the lifecycle of
the superview:
Immediately after setting the constraints, the views should autolayout as
shown above.
Since the superview itself is only (40,40), it should automatically resize
to make the layout possible.
From there onwards, changing the width of any of the subviews should
layout the views again so that they still stick to the layout format.
My approach so far is like so:
- (id)init
{
self = [super initWithFrame:CGRectMake(0, 0, 40, 40)];
if (self) {
self.autoresizingMask = UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
self.v1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
self.v2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
self.v3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[self addSubview:self.v1];
[self addSubview:self.v2];
[self addSubview:self.v3];
NSDictionary *views = @{@"v1" : self.v1, @"v2" : self.v2, @"v3" :
self.v3};
[self addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-10-[v1]-10-[v2]-10-[v3]-10-|"
options:0 metrics:@{@"10":@10} views:views]];
[self layoutIfNeeded];
}
}
but I get the conflicting constraints message:
(
"<NSLayoutConstraint:0xed9f040 H:|-(10)-[UIView:0xed9ad30] (Names:
'|':MyView:0xed9a040 )>",
"<NSLayoutConstraint:0xed9f270
H:[UIView:0xed9ad30]-(10)-[UIView:0xed9c370]>",
"<NSAutoresizingMaskLayoutConstraint:0xeda3770 h=&&& v=-&-
UIView:0xed9c370.midX == 0.5*MyView:0xed9a040.width>",
"<NSAutoresizingMaskLayoutConstraint:0xeda37a0 h=&&& v=-&-
UIView:0xed9c370.width == MyView:0xed9a040.width>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0xed9f270 H:[UIView:0xed9ad30]-(10)-[UIView:0xed9c370]>
My guess is that it has to do with the superview not being able to resize.
But I'm overall somewhat confused about it. Does anyone know what am I
doing wrong?

No comments:

Post a Comment