在tableview上添加按钮 - 无法访问发件人

时间:2012-07-01 19:44:05

标签: xcode uitableview uibutton sender

我已经使用以下代码向我的tableviewcell添加按钮,当按下按钮时我需要知道它是哪一行。所以我已经标记了按钮(playButton viewWithTag:indexPath.row) 问题是,如果我定义目标操作方法(播放)以接收发件人它与“无法识别的选择器”崩溃,任何想法如何知道按钮被按下哪一行或为什么它像这样崩溃 感谢

-(void)configureCell: (UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom] ;
[playButton setFrame:CGRectMake(150,5,40,40)];
[playButton viewWithTag:indexPath.row] ; //Tagging the button
[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];
[cell addSubview:playButton];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *beatCell = nil;
beatCell = [tableView dequeueReusableCellWithIdentifier:@"beatCell"];
if (beatCell == nil){
    beatCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"beatCell"];
}
 [self configureCell:beatCell atIndexPath:indexPath];
return beatCell;

}

-(void) play:(id) sender{
UIButton *play = sender;
NSLog(@"Play %i" , play.tag);

}

2 个答案:

答案 0 :(得分:1)

更改此行的一个字符:

[playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];

[playButton addTarget:self action:@selector(play:) forControlEvents: UIControlEventTouchUpInside];

当您在选择器上包含参数时,冒号实际上对于Objective C运行时很重要,以便能够在您要定位的对象上查找该选择器。

答案 1 :(得分:1)

而不是

[playButton viewWithTag:indexPath.row] ; 

如果您尝试接收UIButton的子视图(我不知道原因),您应该使用setter方法设置标记:

[playButton setTag:indexPath.row];

您还必须将发件人转换为UIButton类型

-(void) play:(id) sender{
UIButton *play = (UIButton *)sender;
NSLog(@"Play %i" , play.tag);
}