memmons
memmons

Reputation: 40492

Centering a UILabel in a UITextView using NSLayoutConstraints

I'm attempting to add a UILabel to a UITextView and have it centered at the top of the textView. Instead of it being centered, it's placed on the left. I suspect this is because the label's intrinsic size takes precedence over the constraint's attempt to stretch it across the view. Not sure how to address the issue though. Here's the code:

self.titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.titleLabel.text = @"Some text that should be centered in the textView";
[self addSubview:self.titleLabel];

NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_titleLabel);

NSArray *hConstraint = 
   [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_titleLabel]-|"
                                               options:0 metrics:nil
                                                 views:viewsDictionary];
[self addConstraints:hConstraint];

NSArray *vConstraint = 
   [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(-50)-[_titleLabel]"
                                               options:0 metrics:nil
                                                 views:viewsDictionary];
[self addConstraints:vConstraint];

Here's a snippet from the iPad simulator of how the label is left justified:

enter image description here

Upvotes: 3

Views: 2636

Answers (1)

matt
matt

Reputation: 534914

You can't use constraintsWithVisualFormat to create centering constraints. You have to set the view's center to a certain position / relation, and the constraintsWithVisualFormat string syntax won't let you do that. You have to use constraintWithItem:attribute:... (or set it up in the nib/storyboard).

Here's code that centers one view in another horizontally:

NSLayoutConstraint* con =
 [NSLayoutConstraint
  constraintWithItem:subview attribute:NSLayoutAttributeCenterX
  relatedBy:0
  toItem:superview attribute:NSLayoutAttributeCenterX
  multiplier:1 constant:0];
[superview addConstraint:con];

To set up a subview as centered in the nib, use the Editor menu to center it horizontally or vertically in its superview and then get rid of any superfluous constraints left over (if any - the nib editor is usually pretty good about getting rid of these automatically when you center something).

Oh, sorry, one more thing: one of the wonderful things about constraints is that you can constrain to any other view. The label may be in front of the text view, but that doesn't mean it has to be constrained to the text view. It can if you want, but then it will scroll with the text view, I think.

That should get you started. Lots more in my book: http://www.apeth.com/iOSBook/ch14.html#_autolayout

Upvotes: 4

Related Questions