2013-05-18 7 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

がクリックされたのtableViewのどの行を知るための最良の方法は、カスタムセルを使用しながら、cellForRowAtIndexPathメソッドでセルボタンのタグ値を設定することである。この

- (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

関連する問題