ios - 表格 View 中的按钮标签重置?

标签 ios objective-c xcode uitableview

我在我的 Storyboard中放置了一个表格 View ,并在单元格中填充了一个以“0”作为标签的按钮。我使用数组填充了 TableView 。假设我的数组中有 20 个元素,这使得它在 tableview 上有 20 个单元格。这是我用来为每个单元格上的按钮添加标签的代码。

- (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;
}

我以为我的代码可以正常工作,但实际上有问题。在单元格 0-5 上,按钮标签是正确的。在接下来的单元格中,标签将再次重置为 0。我做错了什么?

最佳答案

这里还有另一个逻辑问题,你正在重用表格单元格,其中一些你已经将按钮的标签更改为 0 以外的东西。所以如果你得到一个重用的表格单元格,那么有时UIButton 不会有零标记,因此您将无法正确更改它。

关于ios - 表格 View 中的按钮标签重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26504172/

相关文章:

iphone - 迁移到通用应用程序 (iPhone/iPad)

ios - 如何在 iOS 中检测 wifi 或 3G 信号强度?

ios - Xcode 6 删除应用组

ios - 在后台重新加载 UITableView 的数据

ios - Xcode - 保存按钮点击顺序并按保存顺序重播操作?

ios - 如何重新初始化 AVPlayerItem?

ios - 使用 NSPredicate 进行字符串比较

ios - swift:使用restkit输出json

ios - 如何加载第二个 View ,可以通过它看到第一个 View (透明),在 ios 9

ios - UIButton 动画扩展