Zachary Christopoulos
Zachary Christopoulos

Reputation: 643

UIButton Image Changing In Multiple UITableViewCells

I am currently building an iOS app that uses a UITableView with custom UITableViewCells that include a button. What I want to accomplish is having the UIButton's image change on touch up inside. That part is working fine, the issue is when you scroll, suddenly every few row buttons located in the UITableViewCell have this new image. Below is some of my code. Any help would be appreciated.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID = @"CellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];

        //YEP BUT
        yepBut = [[UIButton alloc] initWithFrame:CGRectMake(23, 16, 64, 32.5)];

        [yepBut addTarget:self action:@selector(yepPost:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:yepBut];
    }
    [yepBut setImage:[UIImage imageNamed:@"yepBtn"] forState:UIControlStateNormal];
    return cell;
}

-(void) yepPost:(id) sender{
    //UIButton *clicked = (UIButton *) sender;
    [sender setImage:[UIImage imageNamed:@"yepBtnACT"] forState:UIControlStateNormal];
}

Thanks!

Upvotes: 0

Views: 484

Answers (2)

Zachary Christopoulos
Zachary Christopoulos

Reputation: 643

Subclassing UITableViewCell fixed my issue.

Upvotes: 0

rdelmar
rdelmar

Reputation: 104082

You need to have a property that you set when the button is touched that you check in cellForRowAtIndexPath. So, in the button's method, have a property, say lastTouched (@property (strong,nonatomic) NSIndexPath *lastTouched, or NSInteger if you don't have sections), that you set to the indexPath (or indexPath.row) of the cell in which the touched button resided (gotten from the cell which you get by searching up through the superviews of the button until you find the cell, or by using tags on your buttons equal to the indexPath.row). After that, you have to reloadData or reloadRowsAtIndexPaths to make the change happen. In cellForRowAtIndexPath, you would set your images like this:

if ([self.lastTouched isEqual:indexPath]) {
    [yepBut setImage:[UIImage imageNamed:@"yepBtnACT"] forState:UIControlStateNormal];
else{
    [yepBut setImage:[UIImage imageNamed:@"yepBtn"] forState:UIControlStateNormal];
}

When you first initialize lastTouched, you want to set it to an indexPath that doesn't occur in your table, so nothing will have the yepButAct image until you touch one.

Upvotes: 2

Related Questions