Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; UIImage *unselectedImage = [UIImage imageNamed:@"unselected.png"]; UIImage *selectedImage = [UIImage imageNamed:@"selected.png"]; UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom]; [b setBackgroundImage:unselectedImage forState:UIControlStateNormal]; [b setBackgroundImage:selectedImage forState:UIControlStateSelected]; [b addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; [b setFrame:CGRectMake(0, 0, 40, 40)]; [cell.contentView addSubview:b]; } return cell; } -(void) buttonPressed:(UIButton *)sender { if([sender isSelected]){ //... [sender setSelected:NO]; } else { //... [sender setSelected:YES]; } } </code></pre> <p><strong>edit</strong><br> Your <code>toggleFav</code> code doesn't make much sense.<br> <code>if (favButton == nil) {</code> checks, if <code>favButton</code> is present. But if you are wiring it up with IB, it should always been there at that point. And if it wasn't how could the button call this method? So do it like this:</p> <pre><code>-(void)viewDidLoad { //.... UIImage *unselectedImage = [UIImage imageNamed:@"favUntapped.png"]; UIImage *selectedImage = [UIImage imageNamed:@"favTapped.png"]; [favButton setImage:unselectedImage forState:UIControlStateNormal]; [favButton setImage:selectedImage forState:UIControlStateSelected]; [favButton setFrame:CGRectMake(0, 0, 40, 40)]; //.... } -(IBAction)toggleFav:(UIButton *)sender { if([sender isSelected]){ //... [sender setSelected:NO]; } else { //... [sender setSelected:YES]; } } </code></pre> <p><strong>edit</strong><br> <a href="https://github.com/vikingosegundo/my-programming-examples/tree/master/Favorite">Here</a> you'll find an example project, with a DetaiView, that holds a Button with the 2 states.<br> <strong>Note:</strong> I am saving the information of what button was selected in the NSUserDefaults. You should not do that. Instead you'll want to save it in the model. But as I dont have informations on your model, I am just using NSUserDefaults.</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