如何知道我点击哪个按钮在程序中启动操作?

时间:2021-11-13 23:13:10

I have 3 buttons which call the same function. I want to know inside the function which button called it. Is it possible to know it?

我有3个按钮,它们调用相同的功能。我想在函数里面知道哪个按钮叫它。有可能知道吗?

1 个解决方案

#1


6  

Yes, you can use the sender argument. If you have an IBOutlet called buttonOne, you can check inside the IBAction method like this:

是的,您可以使用sender参数。如果您有一个名为buttonOne的IBOutlet,您可以在IBAction方法中检查如下:

- (IBAction) buttonClicked:(id) sender
{
    if (sender == buttonOne)
    {
        NSLog(@"Button one was pressed.");
    }
}

Alternatively, assign each of your buttons a tag, and use the sender's tag property (the following example assumes that buttonOne was assigned the tag value “1”):

或者,为每个按钮分配一个标签,并使用发送者的标签属性(以下示例假定buttonOne被分配了标签值“1”):

- (IBAction) buttonClicked:(id) sender
{
    if ([sender tag] == 1)
    {
        NSLog(@"Button one was pressed.");
    }
}

#1


6  

Yes, you can use the sender argument. If you have an IBOutlet called buttonOne, you can check inside the IBAction method like this:

是的,您可以使用sender参数。如果您有一个名为buttonOne的IBOutlet,您可以在IBAction方法中检查如下:

- (IBAction) buttonClicked:(id) sender
{
    if (sender == buttonOne)
    {
        NSLog(@"Button one was pressed.");
    }
}

Alternatively, assign each of your buttons a tag, and use the sender's tag property (the following example assumes that buttonOne was assigned the tag value “1”):

或者,为每个按钮分配一个标签,并使用发送者的标签属性(以下示例假定buttonOne被分配了标签值“1”):

- (IBAction) buttonClicked:(id) sender
{
    if ([sender tag] == 1)
    {
        NSLog(@"Button one was pressed.");
    }
}