UITableViewCell自动布局崩溃

时间:2019-07-22 02:57:51

标签: ios objective-c autolayout

我有以下代码可以简单地将UILabel放置在自定义UITableViewCell中。我要实现的是表格单元格左侧/右侧的标签边距为20。它应该是非常基本的,但是会使应用程序崩溃:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        self.label = [[UILabel alloc] init];
        self.label.translatesAutoresizingMaskIntoConstraints = false;

        [self.label.leftAnchor constraintEqualToAnchor:self.contentView.leftAnchor constant:20].active = YES;
        [self.label.rightAnchor constraintEqualToAnchor:self.contentView.rightAnchor constant:20].active = YES;
        [self.label.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:0].active = YES;
        [self.label.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:0].active = YES;

        [self.contentView addSubview:self.label];
    }

    return self;
}

请帮助我弄清楚我在这里做错了什么。谢谢!

1 个答案:

答案 0 :(得分:0)

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        self.label = [[UILabel alloc] init];
        self.label.translatesAutoresizingMaskIntoConstraints = false;

        [self.contentView addSubview:self.label];

        [self.label.leftAnchor constraintEqualToAnchor:self.contentView.leftAnchor constant:20].active = YES;
        [self.label.rightAnchor constraintEqualToAnchor:self.contentView.rightAnchor constant:20].active = YES;
        [self.label.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:0].active = YES;
        [self.label.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:0].active = YES;
    }

    return self;
}

这将起作用