Saturday, June 8, 2013

UITableView tableView willDisplayCell forRowAtIndexPath example in Objective C (iOS).


UITableView tableView willDisplayCell forRowAtIndexPath

Tells the delegate the table view is about to draw a cell for a particular row.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

Parameters of [UITableView tableView willDisplayCell forRowAtIndexPath]
tableView
The table-view object informing the delegate of this impending event.
cell
A table-view cell object that tableView is going to use when drawing the row.
indexPath
An index path locating the row in tableView.

Discussion of [UITableView tableView willDisplayCell forRowAtIndexPath]
A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color. After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out.

UITableView tableView willDisplayCell forRowAtIndexPath example.
So: If you add this method to your table view delegate:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = cell.contentView.backgroundColor;
}
Then in your cellForRowAtIndexPath method you can do:

if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
    cell.contentView.backgroundColor = [UIColor blueColor];
}

Example of [UITableView tableView willDisplayCell forRowAtIndexPath].

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
  UIColor *color = ((indexPath.row % 2) == 0) ? [UIColor colorWithRed:255.0/255 green:255.0/255 blue:145.0/255 alpha:1] : [UIColor clearColor];
  cell.backgroundColor = color;
}

UITableView tableView willDisplayCell forRowAtIndexPath example.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if ((indexPath.row % 2) == 1) {
        cell.backgroundColor = UIColorFromRGB(0xEDEDED);
        cell.textLabel.backgroundColor = UIColorFromRGB(0xEDEDED);
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    else
    {
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }

}

End of UITableView tableView willDisplayCell forRowAtIndexPath example article.