单击按钮时如何传递对象

时间:2012-11-24 05:52:43

标签: objective-c ios xcode

我有一个自定义的tableview单元格,它有一个按钮。单击按钮时,我需要传递tablview的NSIndexPath对象。我能做的是为一个按钮分配一个标签,使用sender接收标签..但我想传递NSIndexPath对象......下面是代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
   static NSString *CellIdentifier = @"shortCodeCell";
   IPadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil)
   {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"KeywordsCell"     owner:nil options:nil];

        for (id currentObject in topLevelObjects)
        {   
            if ([currentObject isKindOfClass:[IPadTableViewCell class]])
            {
                cell = (IPadTableViewCell  *)currentObject;
            }
        }
    }
    // Delete
    [cell.btnDelete addTarget:self action:@selector(onDelete:) forControlEvents:UIControlEventTouchUpInside];

    cell.btnDelete.tag=indexPath.row;

    return cell;
}

-(void)onDelete:(id)sender
{   
     UIButton *btn=(UIButton *)sender;
     NSLog(@"BtnIndexpath to be deleted:%d",btn.tag);
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
     int errorCode = 0;
     kd = [items objectAtIndex:btn.tag];
     BOOL isDeleteKeyword= [ServerAPI deleteKeywordWithId:kd.keywordId :&errorCode];
     dispatch_async (dispatch_get_main_queue (),
                    ^{
                        if (isDeleteKeyword) {
                            [items removeObjectAtIndex:btn.tag];
                            //[tblKeywords deleteRowsAtIndexPaths:[NSArray arrayWithObject:btnIndexPath] withRowAnimation:YES];
                            [self.tblKeywords reloadData];
                        }
                        else return;
                    });
    });
}

2 个答案:

答案 0 :(得分:2)

您可以在" cellForRowAtIndexPath"

中设置以下内容
cell.tag = indexPath.section; 
cell.btnDelete.tag=indexPath.row;

在" onDelete"您可以根据分配的标记创建indexPath。

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[sender tag] inSection:[[sender superview] tag]]

答案 1 :(得分:1)

// I assume your UITableView called tableView
// Using this way you don't need to use tag
-(void)onDelete:(id)sender
{
    UITableViewCell *cell = (UITableViewCell *)[sender superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
}