Sunday, April 3, 2016

ObjectiveC: Randomly Changed Content When TableView is Scrolled

Fixing content randomly displayed when scrolling in ObjectiveC (XCode).
Sometimes when I developing the code to display content using TableView in XCode, I ended up seeing the content will be randomly displayed when scrolling.

After some research, I found that the root cause is the tableView:cellForRowAtIndexPath method. In this method, system expect only cell to be returned, NOT the cell containing binding data. Moreover, setting cell style like color, background is not work in this method too.

So, the correct code this method should be like this
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"CellIdentifier";
    
    FindLocationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"FindLocationTableViewCell" bundle:nil] forCellReuseIdentifier:cellID];
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    }
    
    return cell;
}

and binding data and setting cell style should be done in method tableView:willDisplayCell:forRowAtIndexPath instead.
-(void) tableView:(UITableView *)tableView willDisplayCell:(FindLocationTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary  * locationData = self.listPOIResult[indexPath.row];
    cell.title.text = locationData[@"locationName"];
    cell.image.image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
    
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}

In conclusion,
  • tableView:cellForRowAtIndexPath should return cell object wihtout content. You should set cell structure here like adding the button, imageView .. etc. 
  • tableView:willDisplayCell:forRowAtIndexPath will responsible to do data-binding, style customization, ... etc. You should not change cell structure in this method. 



Happy Coding!

No comments:

Post a Comment