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

您创建按钮分配

将按钮标签设置为 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 回答
0

实际上代码工作正常..您选择哪一行进行测试?是 0 吗?尝试记录行和部分。

还要检查连接的表的插座?以及该插座的参考是否在任何地方发生了变化

否则代码对我来说运行良好

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