0

I have created a custom cell and added a uibutton on it. On tap of that button, Im setting that button selected which changes button's image.

-(IBAction)btnInfoPressed:(id)sender
{
    [btnInfo setSelected:YES];
}

The above method is in the custom cell class. Now when I scroll down, after some cells, some other cell's button is also selected even though I havent tapped that button.

Here is my cellforrowatindexpath method:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"CustomCell";
CustomCell *c = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (c == nil)
{
    c = [[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil] objectAtIndex:0];
}
c.selectionStyle = UITableViewCellSelectionStyleNone;
return c;
}

Any ideas what needs to be done about it?

iAmd
  • 812
  • 1
  • 12
  • 22
  • Show method `[btnInfo setSelected:YES]`. – Geek Jul 07 '13 at 12:02
  • Its the default UIButton property to change its state from Normal to selected or back to normal. – iAmd Jul 07 '13 at 12:08
  • Then should not you use `[sender setSelected:YES]`? – Geek Jul 07 '13 at 12:10
  • It still makes the buttons in other cells selected. – iAmd Jul 07 '13 at 12:12
  • You cannot use the *cell* to store the "selection state" of a row, because cells are *reused*. You have to store that information for each row in some data source and always set the cells's state in cellForRowAtIndexPath. – Martin R Jul 07 '13 at 12:15
  • Its no the selection of a row. Its the selection state of a UIButton inside a custom cell. On tap of that button all I want is to make that BUTTON selected and its working fine. But when I scroll down, some other cell's button also shows selected. – iAmd Jul 07 '13 at 12:17
  • 1
    @AmmadHussain: But the reason is the same. The table view allocates only a finite number of cells. If you scroll down, `dequeueReusableCellWithIdentifier` returns one of the existing cells that have become invisible. Therefore, you have to update the complete state of the cell (including the button's state) in cellForRowAtIndexPath. – Martin R Jul 07 '13 at 12:20
  • @MartinR: You are right. I had to save the state of a cell and all its contents in a data source. Then on every cellforrowatindexpath I have to refresh the contents of cell from that data source. Its working fine now. – iAmd Jul 07 '13 at 12:37

1 Answers1

3

(From my above comments:) You cannot use the cell to store the state of a row, because cells are reused. The table view allocates only a finite number of cells. If you scroll down, dequeueReusableCellWithIdentifier returns one of the existing cells that have become invisible. Therefore, you have to store the row's state in a data source and update the complete state of the cell (including the button's state) in cellForRowAtIndexPath.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382