uitableview单元格中的删除按钮无法正常工作

时间:2011-07-11 11:19:13

标签: iphone uitableview uibutton

我在UItableView中显示注释并在Cell中创建删除按钮。当我删除任何注释时它将删除。我使用了[Tableview reloadData],但它总是从表中删除最后一个单元格,当我下次检查删除的注释时它很好..为什么表视图总是删除最后一个单元格..我的代码是

- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%i",indexPath.row];

   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

   if (cell == nil) {
                    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];


       //delete button in uitableview cell ================================

         deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];

         deleteBtn.frame = CGRectMake(270, 10, 20, 20);

          //[deleteBtn setTitle:@"delete" forState:UIControlStateNormal];

          [deleteBtn setImage:[UIImage imageNamed:@"deletefb.png"] forState:UIControlStateNormal];
          deleteBtn.tag = indexPath.row;

          [deleteBtn addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
                    deleteBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;

           [cell.contentView addSubview:deleteBtn];

            }

            return cell;

    }  

删除方法

- (void )delete:(id)sender {


    UIButton *myDeleteButton = (UIButton *)sender ;




    //delete method of comment

    NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:1];

    [variables setObject:@"delete" forKey:@"method"];


    [fbGraph doGraphPost:[NSString stringWithFormat:@"%@",[(Facebook *)[tableArray objectAtIndex:myDeleteButton.tag]postId]] withPostVars:variables];


     //load tableview 
    [self responseMethod];  //method to load comments
    //show alert
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Deleted"
                                                   message:@"" delegate:nil
                                         cancelButtonTitle:@"Ok" otherButtonTitles:nil ];

    [alert show];
    [alert release];







}

1 个答案:

答案 0 :(得分:3)

尝试将deleteBtn.tag = indexPath.row;移到if (cell == nil)条件之外。

在您当前的设置中,当您重复使用单元格而不是实例化新单元格时,tag将引用旧的indexPath.row而不是新的if (cell == nil) { // Do you other stuff here } deleteBtn.tag = indexPath.row; return cell; 。这可能就是为什么你看到除了预期的细胞之外的细胞被删除的原因。

NSString *identifier = @"someUniqueValue";

此外,您似乎没有掌握重用表格单元格的概念。标识符应该是应用于所有单元格的常量字符串,而不是您在此处设置的动态字符串。例如

{{1}}
相关问题