【问题标题】:UITableViewCell Auto Layout crashedUITableViewCell 自动布局崩溃
【发布时间】:2019-11-29 23:52:28
【问题描述】:

我有下面的代码可以简单地将 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;
}

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

【问题讨论】:

  • 我认为您需要先将label 添加到contentView,然后再对其添加约束。

标签: ios objective-c autolayout


【解决方案1】:
- (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;
}

这会起作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2014-04-27
    • 1970-01-01
    • 2013-10-05
    • 2020-09-24
    相关资源
    最近更新 更多