Reputation: 1468
I'm having some problem with UIButton in a UITableViewCell. I have created a custom tableviewcell in storyboard, using the prototype cell. There are two buttons and I have set a tag to them. The first time the table view is drawn everything is displayed correct, but if I scroll or update the data and call reloadData on tableview, it's not updated correct.
Code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Moment Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSLog(@"Cell: %@", cell);
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
NSArray *row = [mMoment objectAtIndex:indexPath.row];
UILabel *label;
label = (UILabel *)[cell viewWithTag:101];
label.text = [row objectAtIndex:0];
label = (UILabel *)[cell viewWithTag:102];
label.text = [NSString stringWithFormat:@"Koeff: %@",[row objectAtIndex:2]];
UIButton *button;
NSString *btn_title;
button = (UIButton *)[cell viewWithTag:104];
NSLog(@"Button: %@", button);
[button setTag:1];
btn_title = [NSString stringWithFormat:@"%@", [row objectAtIndex:4]];
[button setTitle:btn_title forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:@selector(poangButtonClick:event:) forControlEvents:UIControlEventTouchUpInside];
NSLog(@"Row: %d, Poäng: %@", indexPath.row, btn_title);
label = (UILabel *)[cell viewWithTag:103];
label.text = btn_title;
button = (UIButton *)[cell viewWithTag:105];
[button setTag:2];
btn_title = [NSString stringWithFormat:@"%@", [row objectAtIndex:5]];
[button setTitle:btn_title forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:@selector(poangButtonClick:event:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
The first time button = (UIButton *)[cell viewWithTag:104];
is called on every visible row, everything is correct, but if I scroll or reload the view, button is nil?
Why? Retrieving a label the same way works, and is displayed correctly.
How can I change the label of the buttons in the cell?
Regards
/Fredrik
Upvotes: 1
Views: 1398
Reputation: 848
A quick guess: I see you are resetting the buttons "tag" value which you use to refere to it. So you cant retrive it (after changing it) anymore with the value 104 (after the first creation it is now 1 and 2)
[button setTag:1];
so, you wont get it the next time via
button = (UIButton *)[cell viewWithTag:105];
My assumption is that that the cell does not get deallocated and thus this tag value stays. Maybe this will solve it.
Upvotes: 5