【问题标题】:UISegmentedControl With AutoLayout Misaligns Title具有自动布局的 UISegmentedControl 未对齐标题
【发布时间】:2014-06-11 07:26:51
【问题描述】:

我有一个自定义 UITableViewCell,左侧有一个标签,右侧有一个 UISegmentedControl。我刚刚习惯在代码中使用自动布局,这就是我在自定义单元格中的内容(使用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];
}

我的问题是分段控件的第一个标题总是错位:

这是它在 iOS 6 上的样子:

在 iOS 7 上:

所以第一个问题是:我该如何解决这个问题?

其他切线问题:将自动布局代码放入 updateConstraints 是正确的做法,还是应该只应用一次约束?

【问题讨论】:

  • 要回答您的第二个问题,您不应该将约束放在 updateConstraints 中,除非您放置 BOOL 检查它们是否已经添加,viewDidLoad 或 @ 987654330@ 方法会更好。您还应该添加[self.segmentedControl pinAttribute:NSLayoutAttributeLeft toAttribute:NSLayoutAttributeRight ofItem:self.titleLabel];,因此标题在控件的左侧(以防它们变大)
  • 嗯...似乎切线问题更重要。只需从updateConstraints 中删除约束即可修复它。你什么时候使用updateConstraints?我已经阅读了它的文档,但不是很清楚。

标签: ios objective-c autolayout uisegmentedcontrol


【解决方案1】:

简而言之,来自 UIView.h

如果您在 -updateConstraints 中设置了所有约束,如果没有人进行约束,您甚至可能永远不会收到 updateConstraints。要解决这个先有鸡还是先有蛋的问题,请重写此方法以返回 YES。

+ (BOOL)requiresConstraintBasedLayout {
        return YES; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    相关资源
    最近更新 更多