Search code examples
iosuitableviewcellreusability

Table cell reusebiliy issue in ios


I have added 2 button in a row of table view, for all the rows, and these button clicked as it first time appear in table view , when I scroll the table list the button tapping disable, here is my code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
     static NSString *CellIdentifier = @"ImageOnRightCell";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     cell.selectionStyle = UITableViewCellSelectionStyleGray;
     cell.userInteractionEnabled = NO;
     UIButton *finalPriceBtn=[UIButton buttonWithType:UIButtonTypeCustom];
     UIButton *finalPriceBtn1=[UIButton buttonWithType:UIButtonTypeCustom];

     if (cell == nil)
     {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
         int i=indexPath.row;

         finalPriceBtn.backgroundColor=[UIColor redColor];
         finalPriceBtn.tag=MAINLABEL_TAG;
         finalPriceBtn.frame = CGRectMake(200, 0.0, 100, 50);
         [finalPriceBtn addTarget:self action:@selector(goBtnClk:) forControlEvents:UIControlEventTouchUpInside];
         finalPriceBtn.titleLabel.font=[UIFont systemFontOfSize:12];

         finalPriceBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
         [finalPriceBtn setImage:[UIImage imageNamed:@"man.jpg"] forState:UIControlStateNormal ];
         [cell.contentView addSubview:finalPriceBtn];

         finalPriceBtn1.backgroundColor=[UIColor redColor];
         finalPriceBtn1.tag=SECONDLABEL_TAG;
         finalPriceBtn1.frame = CGRectMake(50.0, 0.0, 80.0, 45.0);
         [finalPriceBtn1 addTarget:self action:@selector(goBtnClk:) forControlEvents:UIControlEventTouchUpInside];
         finalPriceBtn1.titleLabel.font=[UIFont systemFontOfSize:12];

         finalPriceBtn1.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
         [finalPriceBtn1 setImage:[UIImage imageNamed:@"bulk-female.jpg"] forState:UIControlStateNormal ];
         [cell.contentView addSubview:finalPriceBtn1];
     }
     else
     {
         finalPriceBtn = (UIButton *)[cell.contentView viewWithTag:MAINLABEL_TAG];
         finalPriceBtn1 = (UIButton *)[cell.contentView viewWithTag:SECONDLABEL_TAG];

     }
     return cell;
}

Solution

  • It is happening because, each time you are scrolling the tableview, your cells are reused and in that case cell is not nil and the code above the code before the cell==nil, makes the userInteractionEnabled to NO. That's why, your button is not clickable.

    First time those buttons are clickable because they were not allocated, I mean the cell was not allocated and setting any attribute to non-allocated entity makes no effect. Hope you got the point.