I have two labels. I want to be able to move both if one is moved. How do I “attach” them together with NSLayoutConstraints? I can do this in IB, but need to do it in code.
also, what are NSLayoutAttributeBaseline, NSLayoutAttributeLeading, and NSLayoutAttributeTrailing?
EDIT:
centering poweredByLabel (aka label02):
[constraints addObject:[NSLayoutConstraint constraintWithItem:poweredByLabel
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:myImage
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0]];
stack the labels and switch vertically:
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[rememberPasswordSwitch]-10-[rememberPasswordLabel]-10-[versionLabel]-[poweredByLabel]-|"
options:NSLayoutFormatAlignAllBaseline
metrics:nil
views:viewsDictionary]];
which produces the error:
* Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Unable to parse constraint
format: Options mask required views to be aligned on a vertical edge,
which is not allowed for layout that is also vertical.
V:[rememberPasswordSwitch]-10-[rememberPasswordLabel]-10-[versionLabel]-[poweredByLabel]-|……………………………………………………………………………………………..^’
w/out the NSLayoutFormatAlignAllBaseline option, it runs fine (they stack but are not all centered horizontally).
If you need to do this in code, first create the NSLayoutConstraint(s), then add the constraint(s) to the labels’ superview.
There are two ways to create constraints in code.
constraintsWithVisualFormatis usually much more concise thanconstraintWithItem.Then you add the constraint(s) to the labels’ superview:
The Cocoa Auto Layout Guide is short and easy to follow. Give it a read, and I’d be happy to answer any questions you still have.
Edit 1
The option
NSLayoutFormatAlignAllBaselinecreates constraints (in addition to those created by the VisualFormat string) that vertically align the baselines of all specified objects. If your VisualFormat string is creating vertical constraints (it starts with “V:”), you don’t want to use this option. You’d want to use 0 (which means no options), or an option that creates horizontal constraints, like NSLayoutFormatAlignAllCenterX.