Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a best practice for using instance variables with NSLayoutConstraint's Visual Format?

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]];
like image 777
Mike Akers Avatar asked Jan 13 '23 03:01

Mike Akers


1 Answers

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.

like image 159
James Avatar answered Jan 30 '23 20:01

James