Question

I insert custom UIButton on UITableViewCells and when i click it UIButton's pic change to checkmark and when i touch it again it turn to unchecked pic. When i scroll UITableView then i cant make them unchecked , simply cannot change pics. It is like pics getting freeze when i scroll it up. my code is below.

-(void)insertButtonOnCellTw:(UITableView *)tableView IndexPath:(NSIndexPath *)indexPath Cell:(UITableViewCell *)cell {



UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(actionButtonOnCellTw:)
 forControlEvents:UIControlEventTouchDown];
button.tag=indexPath.row;
[button setImage:[UIImage imageNamed:@"imgEmptyCheck.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(285.0f, 20.0f, 35.0f, 35.0f);
[cell addSubview:button];

}

-(void)actionButtonOnCellTw :(id)sender
{
 UIButton *but=(UIButton*)sender;
 NSNumber *intIndexPathRow=[NSNumber numberWithInt:but.tag];
      if([masivCheckedTwCells containsObject:intIndexPathRow])
      {

        [but setImage:[UIImage imageNamed:@"imgEmptyCheck.png"] forState:UIControlStateNormal];
        [masivCheckedTwCells removeObject:intIndexPathRow];
    }
    else

    {
        [but setImage:[UIImage imageNamed:@"imgCheck.png"] forState:UIControlStateNormal];
        [masivCheckedTwCells addObject:intIndexPathRow];
    }


}

I can solve it like after scrolling clean all checkmarked cells and put them again in "for" condition but there is any other and more clear way?

Was it helpful?

Solution

I solved it and want to share for if anyone will stuck in same problem.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

method is reuse every cell over and over again when i scroll it up, so it doesn't create new one but reuse it. With this codes i clean it before reuse it.

NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
for (UILabel *subview in subviews)
{
    [subview removeFromSuperview];
}
for (UIButton *subview in subviews) {
    [subview removeFromSuperview];
}
subviews = nil;

And my last mistake was i was adding buttons on cell like this.[cell addSubview:button]; but it is better add it to contentView like this [cell.contentView addSubview:button];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top