user1046037
user1046037

Reputation: 17695

ios autolayout visual format - alignment

In iOS6, I am using autolayouts.

Question:

Code - Given below is my attempt but however it doesn't provide the desired output. - No errors thrown. V1 is placed correctly but V2 is one the left hand corner of V1

Note - I have explained below in the comments, what I am trying to do.

[v1 addSubView:v2];

v1.translatesAutoresizingMaskIntoConstraints        = NO;
v2.translatesAutoresizingMaskIntoConstraints        = NO;

NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(v1,
                                                              v2);

//I wanted v1 and v2 to be of the same height and wanted the center Y to be aligned together
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[v2(==v1)]"
                                                                         options:NSLayoutFormatAlignAllCenterY
                                                                         metrics:nil
                                                                           views:viewDictionary];


//I wanted v1 and v2 to be of the same height and wanted the center X to be aligned together
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[v2(==v1)]"
                                                                       options:NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:viewDictionary];

[v1 addConstraints:horizontalConstraints];
[v1 addConstraints:verticalConstraints];

Upvotes: 3

Views: 7929

Answers (1)

David Wong
David Wong

Reputation: 10294

Shouldn't just this work?

NSMutableArray *constraints = [NSMutableArray new];

constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[v2]|"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:NSDictionaryOfVariableBindings(v2)];
constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[v2]|"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:NSDictionaryOfVariableBindings(v2)];
[v1 addConstraints:constraints];

What this does is it makes v2 stretch its height and width to the size of its superview, which in this case is v1 and positions it so its right on top of its superview too.

It seems that in your case, you don't need to align the view centerX and centerY. Otherwise, I'm not understanding the context of your question properly.

Upvotes: 2

Related Questions