我正在使用带有Masonry DSL的iOS 6 AutoLayout功能来安排UITableViewCell中的视图。这是我想要实现的布局安排:
containerView
是一个虚拟容器,应该动态调整其大小以适应其内容。在我当前的实现中,这就是我所得到的:
似乎containerView
确实正确地垂直居中,但它没有宽度和高度,因此没有正确显示。如何指示containerView
使其大小符合其内容?代码段附在下面。
谢谢!
UITableViewCell初始化程序
- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {
self.titleLabel = [[UILabel alloc] init];
self.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont smallSystemFontSize]];
self.titleLabel.text = @"ノートタイトル";
self.coverImage = [[UIView alloc] init];
self.coverImage.backgroundColor = [UIColor carrotColor];
self.avatarImage = [[UIView alloc] init];
self.avatarImage.backgroundColor = [UIColor emerlandColor];
self.authorLabel = [[UILabel alloc] init];
self.authorLabel.font = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
self.authorLabel.text = @"著者の名前";
self.containerView = [[UIView alloc] init];
self.containerView.backgroundColor = [UIColor lightGrayColor];
[self.containerView addSubview:self.titleLabel];
[self.containerView addSubview:self.avatarImage];
[self.containerView addSubview:self.authorLabel];
[self.contentView addSubview:self.containerView];
[self.contentView addSubview:self.coverImage];
self.selectionStyle = UITableViewCellSelectionStyleNone;
[self updateConstraintsIfNeeded];
}
return self;
}
UITableViewCell updateConstraints
- (void)updateConstraints
{
[super updateConstraints];
[self.coverImage mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.contentView).with.offset(20);
make.top.equalTo(self.contentView).with.offset(5);
make.bottom.equalTo(self.contentView).with.offset(-5);
make.width.equalTo(self.coverImage.mas_height).multipliedBy(0.75);
}];
[self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.coverImage.mas_right).with.offset(10);
make.centerY.equalTo(self.contentView);
}];
[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.containerView);
make.top.equalTo(self.containerView);
}];
[self.avatarImage mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.titleLabel.mas_bottom).with.offset(5);
make.left.equalTo(self.titleLabel);
make.width.equalTo(@20);
make.height.equalTo(@20);
}];
[self.authorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.avatarImage.mas_right).with.offset(5);
make.centerY.equalTo(self.avatarImage);
}];
}
答案 0 :(得分:24)
我找到了解决自己问题的方法。显然,为了让containerView
动态地调整自身大小,我们必须确保内部的每个元素彼此严格连接以及超视图的边缘(即containerView
)。例如,在VFL中它应该是这样的:"V:|-10-[child1]-5-[child2]-5-|"
所以在我的情况下,我向make.bottom.equalTo(self.containerView)
添加了一个新的约束avatarImage
,现在superview知道如何自己调整高度!