我正在尝试将autolayout用于我正在创建的uitableviewcell子类,我将不胜感激一些关于放置布局约束创建代码的方法的建议。我一直在搜索并找到有关在viewDidLoad方法中添加子视图后添加约束的所有信息。据我所知,viewDidLoad不是uitableviewcell子类的选项。
我正在使用界面构建器来创建自定义单元格并在我的代码中动态分配它。没有什么特别的......我将uitableviewcell子类化,以便我可以为单元格添加自定义uiview。再一次,没有什么特别令人震惊的......当我尝试根据我添加到界面构建器中的单元格的标签来定位我的自定义uiview时,我遇到了困难。
这是创建自定义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];
}
如果我将约束代码放在initSelf的末尾,则没有任何反应。我的_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];
}
谁能告诉我这段代码应该去哪里?当然,每次布局发生时我都会创建重复的约束。
由于
答案 0 :(得分:31)
您需要更新以下约束:
-(void)updateConstraints{
// add your constraints if not already there
[super updateConstraints];
}
将视图添加到superview后,您需要致电[self setNeedsUpdateConstraints]
开始使用它们。通过这样做,渲染运行时将在正确的时间调用updateConstraints
。