选择时在行中添加自定义按钮的情况

时间:2014-03-27 11:57:03

标签: objective-c ios6.0

目标:

  • 每当选择
  • 时,在一行中添加标题为Delete的自定义按钮
  • 每当细胞选择发生变化时将其删除,依此类推,将“删除”添加到最后一次选择。

    (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
        self.myIndexPath=indexPath;
        UIButton *btnCustomDelete=[[UIButton alloc] initWithFrame:CGRectMake(260, 10, 60, 7)];
        [btnCustomDelete setTitle:@"Delete" forState:UIControlStateNormal];
        [tblCellForContactTable.contentView addSubview: btnCustomDelete];  //I think correction wants here  
    
        [btnCustomDelete addTarget:self action:@selector(actionCustomDelete:)  forControlEvents:UIControlEventTouchUpInside];
    }
    
    -(IBAction) actionCustomDelete:(id)sender{
        [arrForMyContacts removeObject:[arrForMyContacts objectAtIndex:myIndexPath.row]];
        [tblForContacts reloadData];
    }
    

但是,它一直没有用。

1 个答案:

答案 0 :(得分:1)

你是对的。您应该将按钮作为子视图添加到实际的UITableViewCell对象中,您可以使用tableView:cellForRowAtIndexPath:数据源方法来实现。

因此,您的实现可能类似于(在创建btnCustomDelete之后):

UITableViewCell * myCell = [tableView cellForRowAtIndexPath:indexPath]
[myCell.contentView addSubview:btnCustomDelete];

请继续阅读。

您的实现不是从表中删除行的健康解决方案。您可以通过实施一些UITableView数据源和委托方法轻松删除操作,而无需添加自定义按钮,如下所示:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [arrForMyContacts removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
相关问题