行动:@select器(showAlert :)如何传递参数在这个showAlert方法?

我将自定义button添加到我的UITableViewCell 。 在该button的操作中,我想调用showAlert:函数,并希望在方法中传递单元格标签。

如何传递showAlert方法中的参数: action:@selector(showAlert:)

这是不可能的。 你必须创build一个符合IBAction的方法

 - (IBAction)buttonXYClicked:(id)sender; 

在这个方法中,你可以创build并调用UIAlertView。 不要忘记使用Interface Builder中的方法来连接button。

如果您想区分多个button(例如,每个表格单元中都有一个),则可以设置该button的标签属性。 然后检查点击从哪个buttonsender.tag。

如果您在Tableviewcell中使用Button,那么您必须为每个单元格的button添加标签值,并将id为方法的addTarget设置为参数。

示例代码:

您必须在cellForRowAtIndexPath方法中input以下代码。

 { // Set tag to each button cell.btn1.tag = indexPath.row; [cell.btn1 setTitle:@"Select" forState:UIControlStateNormal]; // Set title // Add Target with passing id like this [cell.btn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; return cell; } -(void)btnClick:(id)sender { UIButton* btn = (UIButton *) sender; // here btn is the selected button... NSLog(@"Button %d is selected",btn.tag); // Show appropriate alert by tag values } 

Jay的回答非常好,但是如果你有多个部分,它将不能工作,因为indexRow是一个部分的本地部分 。

另一种方法是,如果您在具有多个部分的TableView中使用button,则需要传递触摸事件。

在懒惰的加载器中声明你的button的地方:

 - (UIButton *)awesomeButton { if(_awesomeButton == nil) { _awesomeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [_awesomeButton addTarget:self.drugViewController action:@selector(buttonPressed:event:) forControlEvents:UIControlEventTouchUpInside]; } return _awesomeButton; } 

这里的关键是将你的事件链接到select器方法。 你不能传递你自己的参数,但你可以传递事件。

该button所连接的function:

 - (void)buttonPressed:(id)sender event:(id)event { NSSet *touches = [event allTouches]; UITouch *touch = [touches anyObject]; CGPoint currentTouchPosition = [touch locationInView:self.tableView]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition]; NSLog(@"Button %d was pressed in section %d",indexPath.row, indexPath.section); } 

这里的关键是函数indexPathForRowAtPoint 。 这是UITableView中的一个漂亮的函数,它会在任何时候给你indexPath。 同样重要的是函数locationInView因为你需要在tableView的上下文中触摸,所以它可以精确定位特定的indexPath。

这将允许你知道它是哪个button,在一个表中有多个部分。