如何在这个showAlert方法中传递参数? action:@selector(showAlert:)

6

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

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

3个回答

9

如果您在Tableviewcell中使用按钮,则必须为每个单元格的按钮添加标记值,并设置方法addTarget并将id作为参数。

示例代码:

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

{

     // 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
}

太好了!演算很棒!这个答案非常有启发性!谢谢! - manuelBetancurt

2

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

- (IBAction)buttonXYClicked:(id)sender;

在这种方法中,您可以创建并调用UIAlertView。不要忘记在Interface Builder中将按钮与该方法连接起来。
如果您想区分多个按钮(例如,您在每个表单元格中都有一个按钮),则可以设置按钮的标签属性。然后检查sender.tag以确定点击来自哪个按钮。

你不必使用IBAction。请参考其他答案。 - Joshua Dance

1

Jay的答案很棒,但如果你有多个部分,它将不起作用,因为indexRow是local to a section

另一种方法是,在使用具有多个部分的TableView中的按钮时,传递触摸事件。

在惰性加载器中声明按钮的位置:

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

    return _awesomeButton;
}

关键在于将事件链接到选择器方法上。您不能传递自己的参数,但可以传递事件。
按钮连接的函数:
- (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。
这将使您能够知道在具有多个部分的表格中是哪个按钮。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接