ios - UItableVIew 可重用 Cell 在滚动后在随机单元格添加按钮?

标签 ios uitableview

我有带 ReusableCellWithIdentifier 的 tableview 我正在寻找最佳解决方案。 我不想使用如下所示的 removesubview 方法

if ([cell.contentView subviews]){
    for (UIBUtton *subview in [cell.contentView subviews]) {
        [subview removeFromSuperview];
    }
}

这是我的 cellForRowAtIndexPath 方法。 我习惯用 tag 属性取回 Button。但在滚动时,此按钮会添加到差异部分的差异行中

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdetifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdetifier];
        if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdetifier];
    }


  if ((indexPath.section==1 && indexPath.row==0) || (indexPath.section==3 && indexPath.row==1)) {
         cell.accessoryView = [self buttonWithMap:cell];

       }
   return cell;
}

创建按钮

- (UIButton *)buttonWithMap:(UITableViewCell *)cell
{

    UIButton *btn=(UIButton *)[cell.contentView viewWithTag:101];
    if (btn) {
        return btn;
    }
    else{

    UIButton *btnLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    btnLocation.backgroundColor = [UIColor clearColor];
    btnLocation.frame = CGRectMake(0, 0, 20, 20);
    [btnLocation setImage:[UIImage imageNamed:@"map_location.png"] forState:UIControlStateNormal];
    [btnLocation addTarget:self action:@selector(setAddressBySelectLocation:) forControlEvents:UIControlEventTouchUpInside];
    [btnLocation setTag:101];
        return btnLocation;
    }
}

最佳答案

我相信你需要在不满足条件时将它设置为 nil,否则 tableView 会变得困惑:

if ((indexPath.section==1 && indexPath.row==0) || (indexPath.section==3 && indexPath.row==1)) {
    cell.accessoryView = [self buttonWithMap:cell];
}else{
    cell.accessoryView = nil;
}

关于ios - UItableVIew 可重用 Cell 在滚动后在随机单元格添加按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22861295/

相关文章:

ios - FBSDK 安全网络请求失败 iOS9

objective-c - 添加到数组后保留计数会增加吗?

ios - 在用户输入时更新标签

使用 Storyboard的 iOS 主从应用程序

ios - 分组的 UITableView - 复制设置应用 TableView

uitableview - 防止 UITableviewcell 在重新排序期间变得透明

ios - AppDelegate 中的 Google 和 Facebook 登录 url 处理程序?

ios - 使用 swift 设置 UiStackview 内 UiLabel 的高度

swift - 无法同时满足约束错误

ios - 在 TableViewCell 中启用 UIButton 可在更多 Cell 中启用