Search code examples
iosobjective-cnslayoutconstraint

Understanding visual format constraints in iOS Objective C


I know about setting constraint in InterfaceBuilder ex. Leading, trailing, top, bottom, fixed width etc.. I found some constraint code, I don't know what this code trying to set which constraint, What is exactly meaning of below visual format constraints?

  NSDictionary *binding = @{@"v" : self.view};
    NSDictionary *metrics = @{@"height" : @(self.height)};
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[v]|" options:0 metrics:nil views:binding]];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[v(==height)]|" options:0 metrics:metrics views:binding]];

Solution

  • H:|[v]|

    H represents that the constraints are meant to be added horizontally, similarly V is for vertical.

    | represents super view as indicated by the binding dictionary. NSDictionary *binding

    [v] represents the view itself.

    So H:|[v]| resolves to leading & trailing constraints with 0 constant.

    V:[v(==height)]|

    Similarly here, view is given a bottom constraint and a height constraint with a constant height as mentioned in NSDictionary *metrics.

    Please refer https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html for more information.