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]];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With