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

时间:2016-01-11 00:34:37

标签: ios uibutton selector

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

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

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

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

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

Storyboard connections Storyboard connections 2 所以在下面的代码中

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++;

            }

1 个答案:

答案 0 :(得分:1)

让我们说这是我们的按钮

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