user4537105
user4537105

Reputation:

UITableview duplicate Images by scrolling

I have the following behavior: i have a table with number of rows = 20

i have created in Storyboard UITableView Cell with UIImage. I use the function didSelectRowAtIndexPath for show and hide a image. If i select a row the UIImage xxx.png will be displayed. If i select the same row again then the Image is hidden. That works perfekt but when i scroll down i see rows with images and i have no selected this rows. I will only see the image when i select a row and not duplicates wehen i scroll the table.

Here is my code:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

WorkoutTableVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WorkoutCell" forIndexPath:indexPath];
cell.checkImage= nil;

    if (cell == nil)
    {
        cell = [[WorkoutTableVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WorkoutCell"];


    }

    else{
        //Old cell...get previously createdd imageview
        cell.checkImage = (UIImageView*)[cell.contentView viewWithTag:1001];
    }

long row = [indexPath row];   
cell.lblCell.text = _MyValues[row];
return cell;
  }

I hope you can understand my problem and sorry for my bad english :(

Upvotes: 0

Views: 1099

Answers (1)

pnavk
pnavk

Reputation: 4642

Cells are reused, so you need set the image of the cell each time. You need to have another data source that contains images for each indexPath and use that to set the image for the UIImageView in the cell.

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    WorkoutTableVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WorkoutCell" forIndexPath:indexPath];


    if (cell == nil)
    {
        cell = [[WorkoutTableVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WorkoutCell"];
    }

    long row = [indexPath row];   
    cell.lblCell.text = _MyValues[row];

    // set the image for the UIImageView here
    cell.imageView.image = _MyImages[row];

    return cell;
}

An even better approach would be to have your data source be a key/value pair (like a NSDictionary) with the Keys being the text that goes in the label and the value being the image that should be assigned to the UIImageView.

Upvotes: 1

Related Questions