1

I have a custom UITableViewCell that has a label on the left side a UISegmentedControl on the right. I'm just getting used to using Auto Layout in code, and this is what I have in my custom cell (using UIView+AutoLayout):

-(void)updateConstraints
{
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.segmentedControl.translatesAutoresizingMaskIntoConstraints = NO;

    [self.titleLabel pinToSuperviewEdges:JRTViewPinLeftEdge inset:DB_AUTOLAYOUT_DEFAULT_INSET];
    [self.titleLabel centerInContainerOnAxis:NSLayoutAttributeCenterY];
    [self.segmentedControl pinToSuperviewEdges:JRTViewPinRightEdge inset:DB_AUTOLAYOUT_DEFAULT_INSET];
    [self.segmentedControl pinAttribute:NSLayoutAttributeBaseline
                            toAttribute:NSLayoutAttributeBaseline
                                 ofItem:self.titleLabel];

    [super updateConstraints];
}

My problem is that the segmented control's first title is always misaligned:

This is what it looks like on iOS 6: enter image description here

And on iOS 7: enter image description here

So first question is: How do I fix this?

Other, tangential question: Am I doing the right thing by putting auto layout code in updateConstraints or should I just apply the constraints once?

Shinigami
  • 2,123
  • 23
  • 40
  • To answer your second question, you shouldn't be putting the constraints in `updateConstraints` unless you put a `BOOL` check around if they've been added already, `viewDidLoad`, or the `init` method would be a better place. You should also add `[self.segmentedControl pinAttribute:NSLayoutAttributeLeft toAttribute:NSLayoutAttributeRight ofItem:self.titleLabel];` too, so the title is to the left of the control (in case they can become larger) – Rich Apr 25 '14 at 14:40
  • Hmm... seems like the tangential question was more important. Just taking the constraints out of `updateConstraints` fixed it. When would you use `updateConstraints`? I've read the doc on it but it's not very clear. – Shinigami Apr 25 '14 at 15:09

1 Answers1

8

In short from UIView.h

If you do all of your constraint set up in -updateConstraints, you might never even receive updateConstraints if no one makes a constraint. To fix this chicken and egg problem, override this method to return YES.

+ (BOOL)requiresConstraintBasedLayout {
        return YES; 
}
coco
  • 4,912
  • 2
  • 25
  • 33