Search code examples
iosobjective-cnslayoutconstraintvisual-format-language

NSLayoutRelationConstraint to Visual format constraint


I'm trying to convert a relational constraint to visual format. The subview is of equal width & height to the super view.

Here is my code:

[parentView addConstraint:[NSLayoutConstraint
       constraintWithItem:childView
                attribute:NSLayoutAttributeHeight
                relatedBy:NSLayoutRelationEqual
                   toItem:parentView
                attribute:NSLayoutAttributeHeight
               multiplier:1.0
                 constant:0]];

[parentView addConstraint:[NSLayoutConstraint
       constraintWithItem:childView
                attribute:NSLayoutAttributeWidth
                relatedBy:NSLayoutRelationEqual
                   toItem:parentView
                attribute:NSLayoutAttributeWidth
               multiplier:1.0
                 constant:0]];

How would I convert this to a visual format?


Solution

  • You can do this using two visual format strings, one horizontal, one vertical:

    NSDictionary* views = NSDictionaryOfVariableBindings(parentView, childView);
    NSArray* horzConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[childView(==parentView)]" options:0 metrics:nil views:views];
    NSArray* vertConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[childView(==parentView)]" options:0 metrics:nil views:views];
    

    That, strictly speaking, matches the constraints you showed. It makes the child have the same size as the parent, but does not dictate the position of the child within the parent.

    As Antonis suggested in the comments, you can approach this differently. You can use H:|[childView]| and V:|[childView]| to make the edges of the child match the edges of the parent. This dictates not only the size, albeit indirectly, but the position as well.