ios autolayout visual format - alignment
-
12-12-2019 - |
Question
In iOS6, I am using autolayouts.
- I have 2 views v1 and v2 programatically created.
- v2 is added as a subview to v1
- The constraints for v1 have already been created programatically (not shown here).
- I want v1 and v2 to be of the same size and I want v2 to be placed on top of v1 exactly the horizontal and vertical center matching such that v2 is exactly on top of v1
Question:
- How can I achieve this (preferably using visual format, if its not possible can you suggest alternate approach)?
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];
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow