Sergey
Sergey

Reputation: 1208

UITableViewCell's frame only updated after scrolling

I change the frame of cells (add margins to the left and to the right) according to the code. The problem is cells update their frames only after they disappear and appear again via scrolling. I used table view's - reloadData as well, but it did't help. How do I force cells to be redrawn without scrolling?

- (UITableViewCell *) tableView: (UITableView *) tableView
      cellForRowAtIndexPath: (NSIndexPath *) indexPath {
PersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"TableViewCellID"
                                                            forIndexPath: indexPath];

cell.frame = CGRectMake(20, cell.frame.origin.y, cell.frame.size.width-2*20, cell.frame.size.height);

/* tried any of those
[cell setNeedsDisplay];
[cell setNeedsLayout];
[cell layoutIfNeeded];
*/
return cell;

}

Upvotes: 0

Views: 570

Answers (2)

Sergey
Sergey

Reputation: 1208

The solution to the problem is to override setFrame method of UITableViewCell. This way it perfectly works.

Upvotes: 1

Kris
Kris

Reputation: 155

I'd recommend using .xibs for this. Much easier.

As far as I know, you are not able to change the frame of a cell in that manner. The cell's height is determined by heightForRowAtIndexPath, and the width is set to the width of the tableView.

You may be able to do it in some manner the way you are attempting, but the cleanest way I know is the following.

If you want there to be a margin around the cell, you can:

  • Create a nib for a UITableViewCell with a UIView containing all your views, and place a border using constraints.
  • Embed all your content inside a UIView (lets call this borderedContentView) and place this as the immediate subview of contentView
  • Place constraints relating borderedContentView to the contentView, with the leading, trailing, top and bottom constraints set to the values that create the border width you desire.
  • If your tableView has a backgroundColor, you'll have to set the contentView's backgroundColor to the same color as the tableView's backgroundColor so as to create the illusion of a margin. Do this in the tableView's delegate method willDisplayCell: or in a subclass of UITableViewCell awakeFromNib or other related method.
  • Bask in the glory of your margined cells.

You can also do this programmatically if you prefer not to use interface builder, but it is very easy to do in IB.

Hope this helps.

Upvotes: 1

Related Questions