当tableview滚动时计数值被改变

在这里输入图像说明

这是我的CellForRowAtIndexPath代码

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; { static NSString *simpleTableIdentifier = @"PickAClassCell"; cell = (PickAClassCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PickAClassCell" owner:self options:nil]; cell = [nib objectAtIndex:0]; } cell.CountLabel.tag=1000; [cell.PlusCount addTarget:self action:@selector(PlusButtonSelect :)forControlEvents:UIControlEventTouchUpInside]; return cell; } -(void)PlusButtonSelect :(UIButton *)sender { UILabel *label1 = (UILabel *)[sender.superview viewWithTag:1000]; NSLog(@"%@",label1); int count = [label1.text intValue]; count = count + 1; NSString *Strcount= [NSString stringWithFormat:@"%d",count]; label1.text=Strcount; } 

当我点击加号button计数值增加,但我的问题是当我滚动tableview添加计数值为零(默认位置)。

这是因为你写的

 int count = [label1.text intValue]; count = count + 1; 

每次滚动下一个单元格被创build,计数初始化的button的初始值,而不是与前一个单元格的button的int值。

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

每当表格视图单元出现在屏幕上时,该委托调用。 尝试使用任何variables的帮助来设置计数标签的标签,或尝试通过pickAClassCell添加它。

在你的情况cell.CountLabel.tag=1000; 每当滚动表格视图单元格时,此行都会执行。

尝试这个-

 -(void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //userCountHolder is instance of NSMutableArray. userCountHolder = [NSMutableArray arrayWithObjects:@"0",@"0",@"0", nil]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *simpleTableIdentifier = @"PickAClassCell"; cell = (PickAClassCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PickAClassCell" owner:self options:nil]; cell = [nib objectAtIndex:0]; } cell.CountLabel.text = [userCountHolder objectAtIndex:indexPath.row]; [cell.PlusCount addTarget:self action:@selector(PlusButtonSelect :)forControlEvents:UIControlEventTouchUpInside]; return cell; } -(void)PlusButtonSelect :(UIButton *)sender{ CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition]; int count = [[userCountHolder objectAtIndex:indexPath.row] intValue]; count++; [userCountHolder replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithInt:count]]; [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; } 

cellForRowAtIndexPath试试这个

 if ([self.selectedRows containsObject:indexPath]) { // set count values here cell.countLabel.text = @""; cell.textLabel.textColor = [UIColor grayColor]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } else { //set the normal cells values } 

这里self.selectedRows是一个数组,你必须在用户点击加号或减号button时存储cellIndexPath值。