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

时间:2014-04-04 11:15:25

标签: ios uitableview

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

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

这是我的cellForRowAtIndexPath方法。 我习惯使用tag属性获取Button。但是在滚动的同时,在diff部分的diff行中添加了此按钮。

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

创建Buttonn

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

1 个答案:

答案 0 :(得分:1)

我相信你需要在条件不满足时将其设置为nil,否则tableView会混淆:

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