2013-05-18 40 views
6

我創建了一個具有自定義UITableViewCell的TableView。一個按鈕與tableview的每一行相關聯。現在我想知道點擊一個按鈕的行號,以便我知道哪個行按鈕被點擊。我嘗試了一些在堆棧中找到的東西,但沒有任何工作。如何知道在UITableView中按鈕點擊Tableview單元格的indexPath/row?

我曾嘗試這個代碼 - :

-(void)button1Tapped:(id)sender 
{ 
UIButton *senderButton = (UIButton *)sender; 
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview]; 
UITableView* table = (UITableView *)[buttonCell superview]; 
NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell]; 
NSInteger rowOfTheCell = [pathOfTheCell row]; 
NSLog(@"rowofthecell %d", rowOfTheCell); 
} 

但這也不能正常工作。

感謝您的幫助。

+0

使用標籤是做到這一點的錯誤方法。 – jrturton

回答

20

嘗試用這種

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
      [[cell contentView] setBackgroundColor:[UIColor clearColor]]; 
      [[cell backgroundView] setBackgroundColor:[UIColor clearColor]]; 
      [cell.Mybutton addTarget:self action:@selector(btnCommentClick:) forControlEvents:UIControlEventTouchUpInside]; 
     } 
     cell.Mybutton.tag=indexPath.row; 
    } 

    -(void)btnCommentClick:(id)sender 
    { 
      UIButton *senderButton = (UIButton *)sender; 
      NSLog(@"current Row=%d",senderButton.tag); 
      NSIndexPath *path = [NSIndexPath indexPathForRow:senderButton.tag inSection:0]; 
    } 
+0

它工作得很好! 謝謝! –

+0

歡迎好友... –

+0

這不適用於嵌套表格的情況。當我們有多個會話。 – knocker

1

知道點擊其中的tableView的行,但是使用自定義單元格中的cellForRowAtIndexPath方法中設置單元格按鈕的標籤值的最佳方式。

相關問題