Reputation: 2330
In my application I load a tableView with an array and I've added an UIButton to each row as subView for my need. I know that the reused cell will have the added button So keeping this fact in mind I've Implemented the -cellForRowAtIndexPath method like below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"surgeon"];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"surgeon"];
}
[[cell.contentView subviews]
makeObjectsPerformSelector:@selector(removeFromSuperview)];
//before adding button to the contentView I've removed allSubViews
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(142, 4, 28, 28)];
[btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"infoicon.png"]] forState:UIControlStateSelected];
[btn setSelected:YES];
[btn addTarget:self action:@selector(checkbtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:indexPath.row];
if (indexPath.row==1) {
NSLog(@"CELL %@ CONTNTVEW %@",cell.subviews,cell.contentView.subviews);
}
[cell.contentView addSubview:btn];
return cell;
}
My problem is that the TableView is loaded well at first time But when I scroll the TableView the Button I have added is Removed even though the removing of subView is done before adding the Button as subView help me to get This work
Upvotes: 0
Views: 5956
Reputation: 1716
It appears that removing all of the subviews of the cell's content view is causing the cell to re-create its cell content when you set the text. I've managed to reproduce the problem, and fixed it by using this method instead:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"surgeon"];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"surgeon"];
}
for(UIView *subview in cell.contentView.subviews)
{
if([subview isKindOfClass: [UIButton class]])
{
[subview removeFromSuperview];
}
}
//before adding button to the contentView I've removed allSubViews
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(142, 4, 28, 28)];
[btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"infoicon.png"]] forState:UIControlStateSelected];
[btn setSelected:YES];
[btn addTarget:self action:@selector(checkbtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:indexPath.row];
if (indexPath.row==1) {
NSLog(@"CELL %@ CONTNTVEW %@",cell.subviews,cell.contentView.subviews);
}
cell.textLabel.font=[UIFont systemFontOfSize:12];
cell.textLabel.text=@"A surgeon.";
[cell.contentView addSubview:btn];
return cell;
}
Important note: if you plan on doing any further cell customization, you'll need to remove them manually in the loop as well.
Upvotes: 10