Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's actually pretty easy.</p> <p>Just create a new subclass of UIControl and put it all in there (no need for a separate controller.) Let's call it ToggleImageControl.</p> <pre><code>@interface ToggleImageControl : UIControl { BOOL selected; UIImageView *imageView; UIImage *normalImage; UIImage *selectedImage; } </code></pre> <p>Create a ToggleImageControl for each cell, and add it at the appropriate position.</p> <pre><code>ToggleImageControl *toggleControl = [[ToggleImageControl alloc] initWithFrame: &lt;frame&gt;]; toggleControl.tag = indexPath.row; // for reference in notifications. [cell.contentView addSubview: toggleControl]; </code></pre> <p>Add a UIImageView to contain the image. Add a target for the touch event.</p> <pre><code>- (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]; } </code></pre> <p>Set the UIImageView's image property to update the image; that will trigger the redraw without side-effects.</p> <pre><code>- (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]; } </code></pre> <p>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.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload