2013-07-12 48 views
1

UITableViewCell其中包含UIButton如何通過UIButton標籤獲取UITableView的行和部分?

在我的cellForRowAtIndexPath

cell.toCartBtn.tag = indexPath.row; 
[cell.toCartBtn addTarget:self 
      action:@selector(toCart:) forControlEvents:UIControlEventTouchDown]; 

toCart方法,我需要通過敲擊按鈕標記獲取行和部分。我該怎麼做?

+0

看到我的回答呃http://stackoverflow.com/questions/16621030/how-to-know-the-indexpath-row-on-button-click-of-tableview-cell-in-a-uitableview/16621077#16621077 –

+0

如何使用'cell.accessoryView'? – cahn

+0

謝謝,但我有不止一節) – Romowski

回答

10

看到這個代碼

- (void)toCart:(id)sender 
{ 
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView]; 
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition]; 
    if (indexPath) 
    { 
    ... 
    } 
} 
+0

謝謝!它的工作原理) – Romowski

+0

這仍然是一個非常好的和乾淨的方式來做到這一點。沒有超級視圖或標記黑客。 – brainray

+0

謝謝! @brainray –

0

創建一個自定義的UITableViewCell子和處理觸摸在那裏。

然後爲您的自定義表格視圖單元格定義一個委託,並在創建單元格時將您的表格視圖數據源分配爲委託。

當單元處理觸摸時,向委託發送消息,然後從表視圖中查找索引路徑。

-(void)customTableViewCellButtonPressed:(CustomTableViewCell *)cell { 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    ... 
} 
+0

我也喜歡其他人建議的indexPathForRowAtPoint:方法。 – kball

0

試試這個:

- (void)toCart:(id)sender { 
    CGPoint button1 = [sender convertPoint:CGPointZero toView:self.tblName]; 
    NSIndexPath *index = [self.tableView indexPathForRowAtPoint:button1]; 

    //use index variable 
} 

,也看到了你的錯誤的詳細信息...

Detecting which UIButton was pressed in a UITableView

2

使用這個簡單的代碼,如果UIButton的子視圖是在細胞

- (void)toCart:(id)sender 
{ 
UIButton *senderButton = (UIButton *)sender; 
UITableViewCell *cell=(UITableViewCell*)senderButton.superView; 
NSIndexPath *index = [tableView indexPathForCell:cell]; 
} 
相關問題