4

Let's say I have an instance variable from a superclass named label, and I want to set auto layout constraints using the visual format. If I try to use self.label in the format string, I get parse errors, and I don't have access to _label from a subclass. The workaround that is currently working is below, but it seems kind of ugly. Is there a better way?

    UILabel *label = self.label;
    NSDictionary *views = NSDictionaryOfVariableBindings(label, _textField);

    [self.contentView addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label(==_textField)][_textField(==label)]-|"
                                             options:NSLayoutFormatAlignAllCenterY
                                             metrics:nil
                                               views:views]];

1 Answer 1

9

constraintsWIthVisualFormat takes a views dictionary but it does not HAVE to come from NSDictionaryOfVariableBindings For example:

UILabel *label = self.label;
NSDictionary *views = @{@"label":self.label, @"_textField":_textField};

[self.contentView addConstraints:
 [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label(==_textField)][_textField(==label)]-|"
                                         options:NSLayoutFormatAlignAllCenterY
                                         metrics:nil
                                           views:views]];

I have not tested that so please let me know if I have the order or the syntax wrong so I can fix it, but the point is your dictionary can be arbitrary.

1
  • This is the way to deal with VFL when all you have is a property. I have written about this in some detail here if that helps.
    – jrturton
    Commented Jun 13, 2013 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.