UISegmentedControl With AutoLayout Misaligns Title

不羁岁月 提交于 2019-12-13 18:26:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!