iProRage
iProRage

Reputation: 424

Table view cell's button messes with other cells?

Ok i have a table view that can add and delete cells. For each cell thats added, it gets two buttons in the cell an add and subtract button which adds 1 and subs 1 from the cell's textLabel. But when i press on 1 cells button, it subs from another cells textLabel. Here is my cellForRow method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault   
reuseIdentifier:CellIdentifier];
} 
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];    
cell.textLabel.text = [cells objectAtIndex:indexPath.row];

newBtn = [[UIButton alloc]init];
newBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[newBtn setFrame:CGRectMake(195,20,55,35)];
[newBtn addTarget:self action:@selector(subtractLabelText:)   
forControlEvents:UIControlEventTouchUpInside];
[newBtn setTitle:@"-" forState:UIControlStateNormal];
[cell addSubview:newBtn];

return cell;
}

This next method is the method is the one i hooked up to the subtract button:

- (IBAction)subtractLabelText:(id)sender{

if ( [[cell.textLabel text] intValue] == 0){ 
[newBtn setEnabled:NO];
}
else{
cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text  
intValue] -1];
    }
}

Please help!! Thanks so much! :D

Upvotes: 0

Views: 174

Answers (1)

PengOne
PengOne

Reputation: 48398

You should pass the cell as the argument of subtractLabelText:, otherwise this function does not know which cell its accessing.


The simplest thing that comes to mind for me is to do is to add in a line defining the cell:

- (IBAction)subtractLabelText:(id)sender{

UITableViewCell *cell = (UITableViewCell*)[sender superview]; // <-- ADD THIS LINE

if ( [[cell.textLabel text] intValue] == 0){ 
[newBtn setEnabled:NO];
}
else{
cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text  
intValue] -1];
    }
}

Upvotes: 2

Related Questions