Reputation: 920
I have this code:
UIBarButtonItem *donebutton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonPressed:)];
self.navigationItem.rightBarButtonItem = donebutton;
Now I want to pass some argument to the method :
- (void)doneButtonPressed{}
How to do that ?
Upvotes: 0
Views: 1902
Reputation: 2468
A little hack that can be used in the case of UIBarButtonItem is to use the possibleTitles property which is actually a type of NSSet < NSSString * > which means you can store NSString in it to retrieve it later.
Here is how it can be done:
UIBarButtonItem * rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStylePlain target:self action:@selector(presentNextSegue:) ];
rightButtonItem.possibleTitles = [NSSet setWithObject:@"SegueName"];
self.navigationItem.rightBarButtonItem = rightButtonItem;
-(void)presentNextSegue:(UIBarButtonItem*)sender {
NSLog(@"%@",sender.possibleTitles.allObjects.firstObject);
}
Note: The actual use of possibleTitles property is explained here. This is just a tiny hack :)
Upvotes: 0
Reputation: 38239
Use setAssociatedObject for this if u want to pass object say string then:
Firstly add
#import <objc/runtime.h>
Now
NSString *strText = @"text";
objc_setAssociatedObject(donebutton, "Argument", strText, OBJC_ASSOCIATION_RETAIN_NONATOMIC); // provide button , key , object for passing
and retrieve like this where ever u want your arguments:
NSString *str = objc_getAssociatedObject(donebutton, "Argument"); //using button and key
//remove object associated for button if not needed.
But if u want button reference then
- (void)doneButtonPressed:(id)sender{
UIButton *btnClicked = (UIButton *)sender;
.......
}
Upvotes: 5
Reputation: 7410
You can't do it directly. You should store your parameter in an object elsewhere in your class, then retrieve it when you tap the button.
For example, if you want to pass a NSString, add one in your .h :
@interface myClass {
NSString *param;
}
And in your .m :
- (void)doneButtonPressed {
// Do something with param
}
Upvotes: 2
Reputation: 9935
as you stated a selector like:
@selector(doneButtonPressed:)
it will crash because your method looks like:
- (void)doneButtonPressed{}
But should be:
- (void)doneButtonPressed:(id)sender{}
You can pass your data through sender's tag for example...
Upvotes: 1