简体   繁体   中英

UITableViewCell Auto Layout crashed

I have below code to simply place a UILabel in a custom UITableViewCell . What I want to achieve is the label has a margin of 20 on left/right side of the table cell. It should be very basic but it crashes the app:

- (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;
}

Please help me figure out what I did wrong here. Thanks!

- (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;
}

This will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM