Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, look at this statement in your code:</p> <pre><code>UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"itemCell"]; </code></pre> <p>The method <code>-dequeueReusableCellWithIdentifier</code> will either pull an already created table view cell, or generate a new one if no reusable cell is available.</p> <p>Now review this statement:</p> <pre><code>checkbox = [[UIButton alloc] initWithFrame:(CGRectMake(x,y,20,20))]; … [cell.contentView addSubview:checkbox]; </code></pre> <p>If your cell was just initialized, this code works fine. However, when you scroll your table, your code will start pulling old table view cells that were thrown into the reusable queue. Those old table view cells already contain a <code>UIButton</code>. So every time you call <code>-addSubview:</code> on an old cell, you add duplicate buttons.</p> <p>There are many ways to fix this. Here's one solution for you:</p> <pre><code>static NSInteger const checkboxTag = 123; checkbox = (UIButton *)[cell.contentView viewWithTag:checkboxTag]; if (!checkbox) { checkbox = [[UIButton alloc] initWithFrame:(CGRectMake(x,y,20,20))]; checkbox.tag = checkboxTag; [checkbox setBackgroundImage:[UIImage imageNamed:@"notSelectedButton.png"]forState:UIControlStateNormal]; [checkbox setBackgroundImage:[UIImage imageNamed:@"checkedButton.png"]forState:UIControlStateSelected]; [checkbox setBackgroundImage:[UIImage imageNamed:@"uncheckedButton.png"]forState:UIControlStateHighlighted]; checkbox.adjustsImageWhenHighlighted = YES; [checkbox addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchDown]; [cell.contentView addSubview:checkbox]; } </code></pre> <p><strong>EDIT:</strong></p> <p>Something else worth pointing out. This statement:</p> <pre><code>x =cell.frame.origin.x +100; y = cell.frame.origin.y + 10; </code></pre> <p>By referencing <code>cell.frame</code>, you're creating a <code>UIButton</code> relative to the cell's position in the table view, not the cell itself. Set <code>x = 100; y = 10;</code> to make the offset relative to the the cell's bounds instead.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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