2010-10-04 109 views
1

我在UITableView單元格中添加按鈕。我的代碼是在UITableView中刪除行的UIButton事件

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]; 
+0

代碼說「UIButtonTypeContactAdd」,不能刪除,所以它是有點混亂。 – 2010-10-04 03:48:09

+0

添加時,它將從當前的uitableview中移除並添加到另一個UITableView中。 – saturngod 2010-10-04 04:08:06

回答

3

我相信一個方法是存儲的行數在按鈕標籤

btnView.tag = [indexPath row] 

在行動

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

我使用int row = [sender tag]; – saturngod 2010-10-05 02:15:38

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視圖。

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