Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox image toggle in UITableViewCell

I need some guidance on creating a UITableViewCell that has an image on the left which can be toggled. The image should be tappable and act as a toggle (checkbox).

My parts I'm struggling with are:

  1. How do I detect taps on the image and handle those differently to didSelectRowAtIndexPath?
  2. How do I change the image without performing a [tableView reloadData]?
like image 742
rein Avatar asked Jul 23 '09 12:07

rein


1 Answers

It's actually pretty easy.

Just create a new subclass of UIControl and put it all in there (no need for a separate controller.) Let's call it ToggleImageControl.

@interface ToggleImageControl : UIControl {    BOOL selected;    UIImageView *imageView;    UIImage *normalImage;    UIImage *selectedImage; } 

Create a ToggleImageControl for each cell, and add it at the appropriate position.

ToggleImageControl *toggleControl = [[ToggleImageControl alloc] initWithFrame: <frame>]; toggleControl.tag = indexPath.row;  // for reference in notifications. [cell.contentView addSubview: toggleControl]; 

Add a UIImageView to contain the image. Add a target for the touch event.

- (void) viewDidLoad {    normalImage = [UIImage imageNamed: @"normal.png"];    selectedImage = [UIImage imageNamed: @"selected.png"];    imageView = [[UIImageView alloc] initWithImage: normalImage];    // set imageView frame    [self.view addSubview: imageView];  [self addTarget: self action: @selector(toggleImage) forControlEvents: UIControlEventTouchUpInside];  } 

Set the UIImageView's image property to update the image; that will trigger the redraw without side-effects.

- (void) toggleImage {    selected = !selected;    imageView.image = (selected ? selectedImage : normalImage);      // Use NSNotification or other method to notify data model about state change.    // Notification example:    NSDictionary *dict = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: self.tag forKey: @"CellCheckToggled"];    [[NSNotificationCenter defaultCenter] postNotificationName: @"CellCheckToggled" object: self userInfo: dict];  } 

You will obviously need to massage some stuff. You probably want to pass in the two image names to make it more reusable, and also I'd recommend specifying the notification name string from outside the object as well (assuming you are using the notification method.)

like image 93
Amagrammer Avatar answered Oct 16 '22 15:10

Amagrammer