简体   繁体   中英

Changing images in cells for UITableViewController

I have four different cells that I am trying to add images to and every time that I change the image it adds the image to each cell. I'm trying to add separate images for each cell, but I'm not sure how to do it. Any help would be great! Here's my code:

if ([singletonObj.tempChangelistColor isEqualToString:@"red"]) {

            self.layer.contents = (id)[UIImage imageNamed:@"red.png"].CGImage;

        }else if([singletonObj.tempChangelistColor isEqualToString:@"yellow"]){

          self.layer.contents = (id)[UIImage imageNamed:@"yellow.png"].CGImage;

        }else if([singletonObj.tempChangelistColor isEqualToString:@"green"]){

            self.layer.contents = (id)[UIImage imageNamed:@"green.png"].CGImage;
        }else{

            self.layer.contents = (id)[UIImage imageNamed:@"shop_deal.png"].CGImage;

        }

It's at the bottom of the code with the shop_deal.png .

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"CellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    if (indexPath.row == 0) {
        cell.imageView.image = [self getImageForCell];
    }
    else if (indexPath.row == 1) {
        cell.imageView.image = [self getImageForCell];
    }
    else if (indexPath.row == 2) {
        cell.imageView.image = [self getImageForCell];
    }
    else (indexPath.row == 3) {
        cell.imageView.image = [self getImageForCell];
    }
    return cell;
}
- (UIImage *)getImageForCell{

    UIImage *returnImage;

    if ([singletonObj.tempChangelistColor isEqualToString:@"red"]) {
        returnImage = [UIImage imageNamed:@"red.png"];
    }
    else if ([singletonObj.tempChangelistColor isEqualToString:@"yellow"]){
        returnImage = [UIImage imageNamed:@"yellow.png"];
    }
    else if([singletonObj.tempChangelistColor isEqualToString:@"green"]){
        returnImage = [UIImage imageNamed:@"green.png"];
    }
    else{
        returnImage = [UIImage imageNamed:@"shop_deal.png"];
    }
    return returnImage;
}

if you exactly know the cell no. of which you want to change the image then this will help you.

NSIndexPath *cellIndex = [NSIndexPath indexPathForRow:3 inSection:0]; // suppose cell no is 3 in section 0
UITableViewCell *cell = [_youtTableView cellForRowAtIndexPath:cellIndex];

cell.imageView.image = [UIImage imageNamed:@"shop_deal.png"];

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM