简体   繁体   中英

How to pass on string parameter to another method through button selector?

I have this below delegate method that receives stickerURLString as input:

- (void)selectedSticker:(NSString *)stickerURLString {
    //...
        [self.stickerPreviewButton addTarget:self action:@selector(sendStickerPreviewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    //...
}

And the selector calls this method sendStickerPreviewButtonPressed :

- (void)sendStickerPreviewButtonPressed: (NSString *)stickerURLString {
    [self.delegate InputFunctionView:self sendSticker:stickerURLString];
}

As you can see in order to make this work as expected I have to pass on stickerURLString from selectedSticker method to sendStickerPreviewButtonPressed .

I have tried this:

[self.stickerPreviewButton performSelector:@selector(sendStickerPreviewButtonPressed:) withObject:stickerURLString];

instead of this:

[self.stickerPreviewButton addTarget:self action:@selector(sendStickerPreviewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

But I got "terminating with uncaught exception of type NSException" error.

So anyone knows how to pass on string parameter to another method through button selector?

If you are using performSelector to call the function then you can use this variation

  • (id)performSelector:(SEL)aSelector withObject:(id)object;

Documentation

https://developer.apple.com/reference/objectivec/1418956-nsobject/1418764-performselector


You can also check on this answer where another solution is explained, in my opinion probably more complex but useful

https://stackoverflow.com/a/14161831/1502070

For UIControl object function 1st parameter is id type, passes by control itself , you get uibutton object as a parameter in sendStickerPreviewButtonPressed: function which is not convertible to string , So you got an error, You may pass string By extending UIbutton class by your custom class . then Create button of your own class, anr get you custom property form sender button .

     -(void)sendStickerPreviewButtonPressed:(mycustomButton*)sender{
      //sender.myCustomString
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM