开发者

how to tag UIImage in UITableViewCell

开发者 https://www.devze.com 2023-03-06 01:56 出处:网络
I want to toggle UITableViewCell image - cell.imageView.image. (eg. Red <--> Green) If the current image is green, the image suppose to change to Red when the user click the UITableViewCell.

I want to toggle UITableViewCell image - cell.imageView.image. (eg. Red <--> Green)

If the current image is green, the image suppose to change to Red when the user click the UITableViewCell.

Once I set the image

cell.imageView.image = [UIImage 开发者_JAVA技巧imageNamed:@"Green.png"];

How to detect which image is the cell currently using?

Thanks for any help!


Set the tag on the imageView itself:

#define IMAGE_TAG_GREEN 50
#define IMAGE_TAG_RED   51

-(UITableViewCell*) tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath {
  static NSString *CELL_ID = @"some_cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_ID];
  if(cell == nil) {
     //do setup here...
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_ID] autorelease];
     cell.imageView.tag = //some logic here...
  }
  if(cell.imageView.tag == IMAGE_TAG_GREEN) {
    //...
  } else {
    //...
  }
  return cell;
}

Since tag is an inherited property from UIView, you cannot use it with UIImage itself, but you can use it with UIImageView


It's a bit crude, but you should be able to set up an if statement like the following:

if ([cell.imageView.image isEqual:[UIImage imageNamed:@"Green.png"]]) {
    // image is green;
} else {
    // image is red;
}

I tested it out just to make sure and it works fine


I believe just add a Boolean expression and make it TRUE if it is green and FALSE if it is red. Make this boolean expression extern type so that this could be a global expression. Set the boolean value on clicking the image. I believe this would be of some help.


I'm new to this - but I imagine you could use an if/then statement.

If (cell.imageView.image = [UIImage imageNamed:@"Green.png"]) {
    cell.imageView.image = [UIImage imageNamed:@"Green.png"];
} else
{
    cell.imageView.image = [UIImage imageNamed:@"Red.png"];
}

Or you could go really fancy and use the ternary operator. Something like the following (note the code below is probably wrong - but should hopefully get you started!):

cell.imageView.image = ([UIImage imageNamed:@"Green.png"]) ? 
    cell.imageView.image = [UIImage imageNamed:@"Green.png"]; : 
    cell.imageView.image = [UIImage imageNamed:@"Red.png"];

Let us know how you go with this.

Kolya

0

精彩评论

暂无评论...
验证码 换一张
取 消