问题
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:

And on iOS 7:

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?
回答1:
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;
}
来源:https://stackoverflow.com/questions/23295530/uisegmentedcontrol-with-autolayout-misaligns-title