Subramanian Raj
Subramanian Raj

Reputation: 389

UITableViewCell button change image

In my table cell I am having button like this

cell.btnAddFriend.tag = indexPath.row;
[cell.btnAddFriend addTarget:self action:@selector(addFollow:) forControlEvents:UIControlEventTouchUpInside];

When I click the button it has to call the function addFollow: function, this is working fine.

In the the addFollow function, based on the condition I have to change the image of cell.btnAddFriend

For that I am using this code

[cell.btnAddFriend setImage:[UIImage imageNamed:@"icon_friend.png"]forState:UIControlStateNormal];

If there is one line in the table, this is working fine, if there are more than one line in the table, this is not working because I am not passing the value in which indexpath the button image has to be changed.

Can anyone help me how to set the table cell value through a function.

Upvotes: 0

Views: 911

Answers (1)

Sergii Martynenko Jr
Sergii Martynenko Jr

Reputation: 1407

You can use the following - you actually get your button in addFollow

- (void) addFollow:(UIButton *)sender //this is, actually, button you tapper, so you don't worry which cell it is
{
     [sender setImage:[UIImage imageNamed:@"icon_friend.png"]forState:UIControlStateNormal];
}

However, you should consider the following - if in tableView:cellForRowAtIndextPath: you reuse cells, than you may see, that you have those images set on buttons in cells, you actually didn't tapped. This is possible, if not all your cells fits the screen (you can scroll them out of visibility). In that case, you should keep state, whether button tapped or not.

One way to do it. Declare

@property NSMutableSet *buttonTagsTapped;

addFollow will change

- (void) addFollow:(UIButton *)sender //this is, actually, button you tapped, so you don't worry which cell it is
{
      [sender setImage:[UIImage imageNamed:@"icon_friend.png"]forState:UIControlStateNormal];

      [self.buttonTagsTapped addObject:[NSNumber numberWithInt:sender.tag]];
}

And where you create cell

cell.btnAddFriend.tag = indexPath.row;
if([self.buttonTagsTapped containsObject:[NSNumber numberWithInt:sender.tag]]) {
    [cell.btnAddFriend setImage:[UIImage imageNamed:@"icon_friend.png"]forState:UIControlStateNormal];
}

Upvotes: 1

Related Questions