在哪里创buildsubclassed uitableviewcell的自动布局约束?

我正在尝试为我创build的uitableviewcell子类使用autolayout,我将不胜感激一些关于什么方法放置布局约束创build代码的build议。 我一直在四处search,所有的信息都是在viewDidLoad方法中添加子视图之后添加约束的。 据我所知,viewDidLoad不是一个可用的viewcell子类的选项。

我正在使用接口生成器来创build自定义单元格,并在我的代码中dynamic分配它。 没有什么特别的…我subclass的uitableviewcell,所以我可以添加一个自定义的uiview到单元格。 再次,没有什么特别的地球震惊…我的困难来了,当我尝试定位我的自定义uiview相对于我添加到界面生成器单元格中的标签。

这是创build自定义uiview并将其添加到单元格的内容视图的代码:

- (id)initWithCoder:(NSCoder *)decoder { if ((self = [super initWithCoder:decoder])) { [self initSelf]; } return self; } - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { [self initSelf]; } return self; } - (void) initSelf { // Initialization code _badgeLabel = @""; if (!_customBadge) { _customBadge = [CustomBadge customBadgeWithString:self.badgeLabel]; } // hide the badge until needed self.customBadge.hidden = YES; // add badge to the cell view hierarchy [self.customBadge setTranslatesAutoresizingMaskIntoConstraints:NO]; [self.customBadge setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal]; [self.customBadge setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical]; [self.contentView addSubview:self.customBadge]; } 

如果我把约束代码放在init的末尾,什么都不会发生。 我的_customBadge的位置保持在默认状态。 当我把约束代码放在layoutSubviews中时,应用了定位; 但我很确定这是错误的地方。 代码如下:

 - (void) layoutSubviews { [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.customBadge attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.competence attribute:NSLayoutAttributeRight multiplier:1.0 constant:-14.0]]; [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.customBadge attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.competence attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]]; [super layoutSubviews]; } 

谁能告诉我这个代码应该去哪里? 每次布局发生时,我都会创build重复约束。

谢谢

你将需要更新约束,如:

 -(void)updateConstraints{ // add your constraints if not already there [super updateConstraints]; } 

将视图添加到超级视图后,您需要调用[self setNeedsUpdateConstraints]开始使用它们。 通过这样做,渲染运行时将在正确的时间调用updateConstraints