This is an example of centeing a label in its view using Visual Format Language. Tested in iOS 7, 8 and 9.
Here is the code from view controller that does the trick:
// Center horizontally
var constraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.AlignAllCenterX,
metrics: nil,
views: ["superview":view, "label":label])
view.addConstraints(constraints)
// Center vertically
constraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.AlignAllCenterY,
metrics: nil,
views: ["superview":view, "label":label])
view.addConstraints(constraints)
This code is something like theory of special relativity. I can not say I completely understand it. But it seems to work.
We use two visual format strings:
@"V:[superview]-(<=1)-[label]"
withAlignAllCenterX
option@"H:[superview]-(<=1)-[label]"
withAlignAllCenterY
option
It aligns X and Y centres of the label and its superview. The (<=1)
inequality constraints are needed to allow those centering constraints do their job. If we had just [superview][label]
it would probably stick the edges of the label and its superview together.
If you need help or want to improve this technique feel free to create a pull request, or comment on this stackoverflow answer.