1

I have a simple constraint, which I would prefer to specify using the Asci-art inspired format, however I cannot seem to find an example of this.

NSLayoutConstraint *centerXConstraint = [NSLayoutConstraint constraintWithItem: childView
                                             attribute:NSLayoutAttributeCenterX
                                             relatedBy:NSLayoutRelationEqual
                                                toItem: parentView
                                             attribute:NSLayoutAttributeCenterX
                                            multiplier:1.0f
                                              constant:0.0f]

I've tried a few things such as '|-[childView]-|' but that only forces it X points on the left of it's parent.

1dayitwillmake
  • 2,269
  • 3
  • 26
  • 35

2 Answers2

4

You can't, basically. The visual format is pretty limited in what it can achieve, and anything complex either doesn't work or approaches regex-style levels of "write once, never understand again". It's OK for laying out groups of items that need to maintain spacing between themselves, but for anything else, it isn't worth it.

It's a single constraint, and the code you already have does the right job. I'd stick with that.

If you use constraints often, it is worth using a category on UIView to simplify the common creations since the existing code is quite verbose.

jrturton
  • 118,105
  • 32
  • 252
  • 268
0

It is possible to achieve that result using Visual Format language.

One way to do it is described in this answer: https://stackoverflow.com/a/14917695/1072846

Another way to do it is by using "spacer views", as described in the Creating Equal Spacing Between Views section of the Auto Layout Guide.

Your VFL would look like this:

NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(viewToCenter, spacerView1, spacerView2);

[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[spacerView1(=>1)][viewToCenter][spacerView2(=>1)]|" options:0 metrics:nil views:viewsDictionary]`

Assuming viewToCenter's intrinsicContentSize is set.

Community
  • 1
  • 1
Eric
  • 16,003
  • 15
  • 87
  • 139