如何通过带参数的方法将 UIButton 设置为动作实现?

How to set UIButton an action implement by method with parameters?

是否可以通过此方法将参数传递给选择器?

addTarget:<(nullable id)> action:<(nonnull SEL)> forControlEvents:<(UIControlEvents)>

我创建了一个自定义按钮:

@interface ButtonToShare1 : UIButton
@property (weak, nonatomic) NSArray *jsonArray;
@property (nonatomic, strong) NSString *typeOfIcon;
@end

此外,我将此 class 设置为 Storyboard 中的按钮。

所以在下面的代码中

for (int i=0; i<json.count; ++i) {
            [_buttonsToShare[i] setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[json[i] valueForKey:@"size66"]]];
            ButtonToShare1 *buttonToShare = _buttonsToShare[i];
            buttonToShare.typeOfIcon = [NSString stringWithFormat:@"%@",[json[i] valueForKey:@"name"]];
            [_buttonsToShare[i] addTarget:self action:@selector(sendIcon:) forControlEvents:UIControlEventTouchUpInside];
         }

我有一个例外*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton setTypeOfIcon:]: unrecognized selector sent to instance 0x7fe5661787b0' 在行

             buttonToShare.typeOfIcon = [NSString stringWithFormat:@"%@",[json[i] valueForKey:@"name"]];

P.S:即使我执行以下操作也会发生同样的情况:

 for (ButtonToShare1 *myButton in self.buttonsToShare) {
                [myButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[json[i] valueForKey:@"size66"]]];

                myButton.typeOfIcon =[NSString stringWithFormat:@"%@",[json[i] valueForKey:@"name"]];
                [myButton addTarget:self action:@selector(sendIcon:) forControlEvents:UIControlEventTouchUpInside];
                i++;

            }

假设这是我们的按钮

 @interface CustomButton : UIButton
 @property (weak, nonatomic) NSArray *yourArray; // weak is fine
 @end

执行文件

@implementation CustomButton
@end

您正在从故事板创建按钮并使用 IBAction 或以编程方式:

CustomButton *button = [[CustomButton alloc] init];
button.yourArray = //array here;
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

点击方法

- (IBAction)buttonTapped:(CustomButton *)button {
    // button.yourArray
}