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:
didSelectRowAtIndexPath
?[tableView reloadData]
?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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With