dado728
dado728

Reputation: 55

iOS - UIButton in selected cells of UITableView

I'm facing a paramount problem that led me almost to toss my computer out of the window. I'm trying to create a button only on some cells, I don't have any problem about triggering the action, but when I scroll down the table and I come back to the first cells the button is created on other cells. In other words, if cells 1 and 3 are supposed to have the button, when the tableview is created they are the only ones having the button. When I scroll down and up again also cell 2, 3 and 4 have the button (there is not a specific rule). The button is also working perfectly but it is not supposed to be there!

static NSString *CellIdentifier = @"Cell";
    OpinionCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell= [[OpinionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

...some influent code.......

if(([[aComment objectForKey:@"TypeMsg"] intValue]==310)&&([[parentMessage objectForKey:@"TypeMsg"] intValue]==310)){
            UIButton *_openReplyButton = [[UIButton alloc] initWithFrame:CGRectMake(280, 5, 20, 20)];
            [_openReplyButton setImage:[UIImage imageNamed:@"reply_button.png"] forState:UIControlStateNormal];
            [_openReplyButton addTarget:self action:@selector(addRowsForShowReply:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:_openReplyButton];
            NSLog(@"%@", [aComment objectForKey:@"Message"]);
        }

Thank you very much for your help!

Upvotes: 1

Views: 212

Answers (2)

ldindu
ldindu

Reputation: 4380

You can use following code to remove the subviews from UITableViewCell right after when the cell is dequeued or initialised as it will remove all its subviews or you can follow what dado728 has mentioned above.

[[cell subviews] performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];

Upvotes: 0

architectpianist
architectpianist

Reputation: 2552

This is a classic problem for UITableView. It took me ages to figure out the dequeuing and reusing process that the table view does. Here's what should fix it.

Move the code to initialize the button into the part that checks whether cell == nil. This is because you're not supposed to add subviews to cells that have just been dequeued, because you don't know whether that cell has already had the subview added to it. Also, you should either set a tag for the button or make it a property of the OpinionCell. That way you can access it later.

Then, if you have determined that the button should be visible, set cell.replyButton.hidden = NO or [cell viewWithTag:kMyButtonTag].hidden = NO. Very importantly, you should set it to be hidden in an else clause. Otherwise, the button will show on seemingly random cells.

Hope this helps!

Upvotes: 1

Related Questions