Tuesday, February 11, 2014

Laying Out Subviews In A Reused UITableViewCell

Last night I ran into a frustrating issue where it appeared that reused UITableViewCell objects were coming into view with highlighting set. I tried every type of interaction-related API I could for the cell and for the table view with no effect. I went to bed bleary-eyed from reading countless Stack Overflow posts and immensely frustrated. 

I hate committing to Git with known issues.

So tonight I'm watching some awesome snowboard action from Sochi, with my laptop open, when suddenly I recall another issue I had before that had to do with repeatedly laying out the same subviews to give another view the appearance of being highlighted. (I am using sub-1.0 alpha values for certain things.) 

So with a bit of debugging I found out that even re-used UITableViewCell objects, once brought into view, always call their layoutSubviews method. Since I was customizing UITableViewCell and was putting my custom content in the layoutSubviews method, the reuse of my custom cell was overlaying views over and over. 

The answer lay in the UITableViewCell prepareForReuse method along with an ivar:

#pragma mark - UIView

- (void) layoutSubviews
{
    [super layoutSubviews];
    
    if (!_isBeingReused)
    {
       [[self contentView] addSubview:[self myCustomContentView]];
    }
}

#pragma mark - UITableViewCell

- (void) prepareForReuse
{
    _isBeingReused = YES;
}

Boom.

No comments:

Post a Comment