Mithuzz
Mithuzz

Reputation: 1091

How to load images to seletcted rows in a UITableView?

I am trying to load image into a tableview row. The scenario is, i have two arrays say

nameID = [NSString stringWithFormat:@"01",@"02",@"05",@"06",@"07",@"08",@"09",nil];

and

testID = [NSString stringWithFormat:@"02",@"05",@"07",@"09",nil];

and I loaded the nameID values to the tableview. Now I need to load images to the row, if the indexPath.row value contains in testID. I tried to load, at first time it is working but when I scroll, the image is loading to all rows as I scroll. So, how can I implement that in a proper way? Here is my code:

NSString *temp1 = [friendsID objectAtIndex:indexPath.row];
if ([alertArray containsObject:temp1]) {
    tickImg.image = [UIImage imageNamed:@"tick.png"];
    [cell.contentView addSubview:tickImg];
}

Please share your thoughts. Thanks.

Upvotes: 0

Views: 200

Answers (1)

Jitendra Singh
Jitendra Singh

Reputation: 2181

Hope this snippet will help you.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    //configure cell
    NSString *imageName = [NSString stringWithFormat:@"%02d",indexPath.row]; //convert row number to string with format ##
    if ([testId containsObject:imageName]) {
        UIImage *img = [UIImage imageNamed:imageName];
        cell.imageView.image = img;
    }
    cell.textLabel.text = [nameId objectAtIndex:indexPath.row];

    return cell;
}

Upvotes: 1

Related Questions