1

私のテーブルビューでは、各セルにボタンがあります

UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
editButton.frame = CGRectMake(281,0, 20, 50);
UIImage *editButtonImage = [UIImage imageNamed:@"edit.png"];
[editButton setImage:editButtonImage forState:UIControlStateNormal];
[editButton setBackgroundColor:[UIColor clearColor]];
[editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:editButton];

そしてボタンアクションはこれ

-(IBAction)editButtonAction:(id)sender{
     UIButton *btn = (UIButton*) sender;
     UITableViewCell *cell = (UITableViewCell*) btn.superview.superview;
     NSIndexPath *indexPath =[self.table indexPathForCell:cell]; 
     int row = indexPath.row;
     NSLog(@"Selected row is: %d",row);
}

テーブル ビューで選択した行のボタンをクリックすると、常に 0 になります。そして任意のコード

4

4 に答える 4

1

代替ソリューション:

.
.
editButton.tag = indexPath.row;
[editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
.
.

-(IBAction)editButtonAction:(id)sender{
UIButton *btn = (UIButton*) sender;
NSLog(@"Selected row is: %d",btn.tag);
}
于 2012-09-18T06:48:33.967 に答える
0

実際、コードは問題なく動作します。テスト用に選択した行はどれですか?それは 0 ですか? 行とセクションの両方をログに記録してみてください。

また、接続されているテーブルのコンセントを確認し、そのコンセントの参照がどこかで変更されたかどうかを確認します

それ以外の場合、コードは問題なく動作します

    NSLog(@"Row: %d\n ,Section :%d",indexPath.row,indexPath.section);;
于 2012-09-18T07:18:30.920 に答える
0

ボタンの割り当てを作成します

ボタンタグをtableViewセルのインデックスとして設定します。

[editButton setTag:indexPath.row];

ボタンで

-(IBAction)editButtonAction:(id)sender
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[sender tag] inSection:0]];

    NSLog(@"Selected Cell is: %@",cell);
    NSLog(@"Selected row is: %d",[sender tag]);
}
于 2012-09-18T06:51:56.217 に答える
0

この方法では..

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

次の行を追加します。

  button.tag = indexPath.row;

そして、このボタンアクションでは、

 -(IBAction)editButtonAction:(id)sender

次の行を追加します。

int row = [sender tag];
于 2012-09-18T06:52:43.890 に答える