按钮在滚动后显示在UITableView单元格中

按钮在滚动后显示在UITableView单元格中,uitableview,Uitableview,我不确定这段代码出了什么问题,但是在一个我没有添加按钮的单元格中(我有一个“如果”复选框,检查是否需要添加按钮),按钮在向下滚动然后再次向上滚动后出现 这是tableview中单元格生成函数的代码 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CLASSshopCell *cell = [tableView dequeueRe

我不确定这段代码出了什么问题,但是在一个我没有添加按钮的单元格中(我有一个“如果”复选框,检查是否需要添加按钮),按钮在向下滚动然后再次向上滚动后出现

这是tableview中单元格生成函数的代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CLASSshopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shopCell"];

    SKProduct * product = (SKProduct *) _products[indexPath.row];
    cell.titleCell.text = product.localizedTitle;
    cell.descCell.text  = product.localizedDescription;

    [_priceFormatter setLocale:product.priceLocale];
    cell.priceCell.text = [_priceFormatter stringFromNumber:product.price];


    // already yours, so no cart button
    if ([[CLASSIAPHelper sharedInstance] productPurchased:product.productIdentifier]) {
        cell.priceCell.text = @"Already yours";
    } else {
          UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
          UIImage *btn = [UIImage imageNamed:@"cart.png"];
          UIImage *btnh = [UIImage imageNamed:@"cartHover.png"];

          [buyButton setBackgroundImage:btn forState:UIControlStateNormal];
          [buyButton setBackgroundImage:btnh forState:UIControlStateHighlighted];
           buyButton.frame = CGRectMake(cell.bounds.size.width - 40,40, 24, 24);
           buyButton.tag = indexPath.row;

        [buyButton addTarget:self action:@selector(buyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
         [cell.contentView addSubview:buyButton];
    }

    return cell;
}

记录一些我没有注意到的东西,没有什么特别的,条件总是经过验证的。你有什么想法吗?

我用另一个问题的部分代码来解决。 基本上,我现在是循环进入细胞,清除所有的按钮,然后再做一次测试

for (UIView *subview in [self.contentView subviews]) 
{
    if ([subview isKindOfClass:[UIButton class]]) 
    {
        [subview removeFromSuperview];
    }
}

添加按钮的单元格最终将被重用。这就是为什么你会把按钮放在错误的单元格上;)

作为一种解决方案,您应该为有按钮和没有按钮的单元格使用不同的重用标识符