Friday, June 7, 2013

UITableViewCell backgroundView example in Objective C (iOS).

UITableViewCell backgroundView

The view used as the background of the cell.

@property(nonatomic, retain) UIView *backgroundView

Discussion of [UITableViewCell backgroundView]
The default is nil for cells in plain-style tables (UITableViewStylePlain) and non-nil for grouped-style tables UITableViewStyleGrouped). UITableViewCell adds the background view as a subview behind all other views and uses its current frame location.

UITableViewCell backgroundView example.
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
    cell.backgroundView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"list-view-bg.png"] highlightedImage:[UIImage imageNamed:@"list-view-bg.png"]];

Example of [UITableViewCell backgroundView].
The best place to set a background view for a cell is the tableView:willDisplayCell:forRowAtIndexPath: method.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]];

UITableViewCell backgroundView example.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {   
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    // New!
    cell.backgroundView.clipsToBounds = YES;

    UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"menu.0%d.large.png", indexPath.row+1]]];
    UIImageView *selectedBgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"menu.0%d.large.selected.png", indexPath.row+1]]];   
    // New! = CGPointMake(160, 25); // Adjust the y-Value to be exactly half of the height of your cell
    bgView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin; // Not quite sure whether these two will work, maybe you have to play a little with the Masks

    cell.backgroundView = bgView;
    cell.selectedBackgroundView = selectedBgView;       
    [bgView release];
    [selectedBgView release];
return cell;

End of UITableViewCell backgroundView example article.