views:

33

answers:

1

Ive added a uiimageview as a subview to my cell.and then put a label on top of it so that it would seem like a button.But whwn the table is scrolled up or down the image seems to get painted again.This turns extremely ugly as my image has transparency effect which is lost as soon as it goes out of view and comes back.???

+2  A: 

Ok, I'll try to guess what your code looks like :)

If images are painted multiple times that means you add them each time table view queries data source for a cell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView @"SomeID"];
    if (cell == nil) {
        // Create cell
    }
    UIImageView *imView = ... //Create and initialize view
    [cell.contentView addSubview:imView];
    ...
    return cell;
}

So each time your cell appears on screen (after user scrolls the table) new instance of image view is added to the cell. The correct approach is to add image view only once - when cell is created and then obtain and setup the existing image view:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView @"SomeID"];
    if (cell == nil) {
        // Create cell
        UIImageView *imView = ... //Create and initialize view
        imView.tag = 1000; // or any other int value
        [cell.contentView addSubview:imView];
    }
    UIImageView *iView = (UIImageView *)[cell.contentView viewWithTag:1000];
    iView.image = ...// set required image
    ...
    return cell;
}

So with this approach each time the cell is reused by table view the existing image view is populated with the image appropriate for the current row.

I used a seperate identifier for each cell.

Usually it is not a good idea - in this case table won't be able to reuse its cells and you may get serious performance troubles

Vladimir
@Vladimir:this is great!its working now.But i made one change.instead of adding the image later i added it to the imView at time of creation itself.It still works.Why did you add the image later?
Mithun Madhav
@Mithun - I added image later assuming that each cell may have different images to be able to reuse any old cell for any row. if all images are the same you indeed can set it just once on cell creation
Vladimir