Haagenti
Haagenti

Reputation: 8144

iOS Creating TableViewCell in Code

I'm trying to create a UITableViewCell in code using autolayout. But I keep getting this error :

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. DXCell's implementation of -layoutSubviews needs to call super.

This is my current code:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
   self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
   if (self) {
     _image = [UIImageView new];
     _image.translatesAutoresizingMaskIntoConstraints = NO;
     _image.image = [UIImage imageNamed:@"image"];

     [self addSubview:self.clubImage];
     self.shouldUpdate = YES;
     [self setNeedsUpdateConstraints];
   }
   return self;
}

- (void) updateConstraints {
  if (self.shouldUpdate) {
    NSDictionary * views = @{@"club" : self.clubImage};
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-6-[club(48)]|" options:0 metrics:nil views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6-[club(48)]-6-|" options:0 metrics:nil views:views]];
     self.shouldUpdate = NO;
  }

  [super updateConstraints];
}

As you can see I'm not overriding layoutSubviews? So I do not understand the error.

The cell is registered through the class and is called in the datasource method:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   return [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
}

Answer: I am adding the view directly instead of using contentView. This caused the problem and is fixed now

Upvotes: 0

Views: 120

Answers (2)

Anindya Sengupta
Anindya Sengupta

Reputation: 2579

Try replacing the line [self setNeedsUpdateConstraints]; with the following

[self layoutIfNeeded];
[self updateConstraintsIfNeeded];

Upvotes: 0

Maen
Maen

Reputation: 10700

DXCell's implementation of -layoutSubviews needs to call super.

So, check the method layoutSubviews under DXCell.m (your custom cell), and call

[super layoutSubviews];

at the beginning of the override.

Upvotes: 1

Related Questions