UITableView中删除行的UIButton事件

时间:2010-10-04 03:28:46

标签: iphone objective-c ios4

我在UITableView单元格中添加了按钮。我的代码是

UIButton *btnView = [[UIButton buttonWithType:UIButtonTypeContactAdd] retain];
    btnView.frame = CGRectMake(280.0, 8.0, 25.0, 25.0);

    //[btnView setImage:[UIImage imageNamed:@"invite.png"] forState:UIControlStateNormal];
    [btnView addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:btnView];
    [btnView release];

我的按钮操作是

- (void)action:(id)sender
{

}

我想知道,点击时如何获取当前表行索引。我想在点击按钮时删除表格行。

编辑:: 我找到了一种用动画删除的方法

[listOfItems removeObjectAtIndex:indexPath.row];

[self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];

3 个答案:

答案 0 :(得分:3)

我认为一种方法是将行号存储在按钮标记

btnView.tag = [indexPath row]

在行动中

- (void)action:(id)sender
{
    UIButton * btn = (UIButton)sender;
    int row = btn.tag;
}

答案 1 :(得分:0)

我通常使用这种方法:

- (IBAction)buttonAction:(id)sender {
    UIButton *button = sender;
    UIView *contentView = [button superview];
    UITableViewCell *cell = (UITableViewCell *)[contentView superview];
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];

    //Do something
}

根据UITableViewCell的布局,您可能需要更深入地遍历TableViewCell Views。

答案 2 :(得分:0)

http://nshipster.com/associated-objects/使用围绕行的NSNumber的关联对象或索引路径本身作为关联对象

//when you create the button
objc_setAssociatedObject(button, associationKeyForButton, [NSNumber numberWithInteger:indexPath.row], OBJC_ASSOCIATION_RETAIN_NONATOMIC);


//in the touch up inside handler to get the row back.
NSNumber* rowNumber = objc_getAssociatedObject(sender, associationKeyForButton);