user578386
user578386

Reputation: 1061

How to pass an object when a button is clicked

I have a custom tableview cell which has a button. I need to pass the NSIndexPath object of tablview when the button is clicked. I am able to do is assign a tag to a button, receive the tag using sender..but I want to pass the NSIndexPath object...below is the code.

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

Upvotes: 0

Views: 230

Answers (2)

sunkehappy
sunkehappy

Reputation: 9091

// 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];
}

Upvotes: 1

Paramasivan Samuttiram
Paramasivan Samuttiram

Reputation: 3738

You can set the following in "cellForRowAtIndexPath"

cell.tag = indexPath.section; 
cell.btnDelete.tag=indexPath.row;

And in "onDelete" you can create indexPath based on tags assigned.

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

Upvotes: 2

Related Questions