我正在尝试在以编程方式实现的自定义 UITableViewCell 上使用 iOS 6 的新自动布局功能。我添加了 addConstraint 调用,它一开始可以正常工作——直到我滚动。当我滚动布局后回到单元格时,布局被丢弃。垃圾我的意思是字段之间的边距都是错误的(太大,远远超出单元格的大小)。我推测这与 dequeueReusableCellWithIdentifier 方法给我留下一个“脏”单元格有关,就像你发现自己需要重新初始化单元格内的字段一样,但我似乎无法做任何事情来哄它正确渲染再次。在返回单元格之前,我尝试调用 [self.contentView updateConstraints]。我已经尝试破坏约束并重新创建它们。不仅不行,但是如果在 layoutSubviews 中尝试它,它会冻结在某种无限循环中。有任何想法吗?
这是建立约束的代码。它位于 initWithStyle:reuseIdentifier:
[self.completedLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.nextSetHeaderLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.nextSetDetailLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.youWillLearnHeaderLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.youWillLearnDetailLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.contentView removeConstraints:[self.contentView constraints]];
NSDictionary *views = NSDictionaryOfVariableBindings(_completedLabel, _nextSetHeaderLabel, _nextSetDetailLabel, _youWillLearnHeaderLabel, _youWillLearnDetailLabel);
[self.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_completedLabel]-5-|"
options:0
metrics:nil
views:views]];
[self.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_nextSetHeaderLabel]-5-|"
options:0
metrics:nil
views:views]];
[self.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_nextSetDetailLabel]-5-|"
options:0
metrics:nil
views:views]];
[self.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_youWillLearnHeaderLabel]-5-|"
options:0
metrics:nil
views:views]];
[self.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_youWillLearnDetailLabel]-4-|"
options:0
metrics:nil
views:views]];
[self.contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_completedLabel]-12-[_nextSetHeaderLabel]-0-[_nextSetDetailLabel]-12-[_youWillLearnHeaderLabel]-0-[_youWillLearnDetailLabel(>=20)]-1-|"
options:0
metrics:nil
views:views]];