utsabiem
utsabiem

Reputation: 920

Pass argument in selector of right bar button item

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

Answers (4)

n.by.n
n.by.n

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

Paresh Navadiya
Paresh Navadiya

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

rdurand
rdurand

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

Stas
Stas

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

Related Questions