Hanny Udayana
Hanny Udayana

Reputation: 388

Button tag in table view resets?

I put a tableview in my storyboard, and filled the cell with a button with "0" as the tag. I populated the tableview using an array. Let's just say I have 20 elements in my array, that makes it 20 cells on the tableview. This is the code I'm using to give tags to the button on each cell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _tblCart) {
        static NSString *cellIdentifier = @"CartCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;

        UIButton *btn = (UIButton *)[cell viewWithTag:0];
        [btn setTag:indexPath.row];
        [btn addTarget:self action:@selector(logTag:) forControlEvents:UIControlEventTouchUpInside];

        return cell;
    }
    return nil;
}

I thought my code will work just fine, but actually there is something wrong. On cell 0-5, the button tag is correct. On the following cell the tag will reset again to 0. What am I doing wrong?

Upvotes: 0

Views: 142

Answers (3)

Bartek Chlebek
Bartek Chlebek

Reputation: 1665

Both Flexicoder and l0gg3r are correct. Also, relying on button's tag as row identifier is a bit of a clunky workaround in my opinion. Consider this approach:

- (void)logTag:(UIButton *)sender {
  NSIndexPath *indexPath = [_tblCart indexPathForRowAtPoint:[_tblCart convertPoint:sender.center fromView:sender]];
  // do your stuff knowing which indexPath the button belongs to
}

Upvotes: 0

Flexicoder
Flexicoder

Reputation: 8501

There is also another logic problem here, you are reusing table cells, some of which you've changed the tag of the button to something other than 0. So if you get a reused tablecell, there will come a time that the UIButton won't have a tag of zero and therefore you won't be able to change it correctly.

Upvotes: 1

l0gg3r
l0gg3r

Reputation: 8954

Don't set 0 as a tag identifier to views.
All UIViews have a tag by default 0.

So [cell viewWithTag:0];
probably will return the contentView of the cell.

Upvotes: 1

Related Questions