6

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

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

4

3 回答 3

9

如果您在 Tableviewcell 中使用 Button,那么您必须为每个单元格的按钮添加标签值,并将方法 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
}
于 2009-10-02T10:44:40.547 回答
2

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

- (IBAction)buttonXYClicked:(id)sender;

在此方法中,您可以创建和调用 UIAlertView。不要忘记将按钮与 Interface Builder 中的方法连接起来。

如果您想区分多个按钮(例如,每个表格单元格中有一个),您可以设置按钮的标签属性。然后检查 sender.tag 点击来自哪个按钮。

于 2009-10-02T09:53:21.827 回答
1

Jay 的回答很好,但是如果您有多个部分,它将无法工作,因为 indexRow 是部分的本地

如果您在具有多个部分的 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。

这将允许您在具有多个部分的表格中知道它是哪个按钮。

于 2013-05-01T17:52:03.873 回答