How to associate a method with this button?
-
29-09-2019 - |
Question
I have a navigation bar button that displays both image and text. This is the code:
UIImage *saveImage = [UIImage imageNamed:@"star.png"];
UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
[saveButton setBackgroundImage:saveImage forState:UIControlStateNormal];
[saveButton setTitle:@"Save" forState:UIControlStateNormal];
saveButton.frame = (CGRect) {
.size.width = 100,
.size.height = 30,
};
UIBarButtonItem *barButton= [[UIBarButtonItem alloc] initWithCustomView:saveButton];
[self.navigationItem setRightBarButtonItem:barButton animated:YES];
I tried this
[barButton setAction:@selector(saveArray)];
but it doesn't work.
Solution
Remember that you must specify target as well. You can set action/target to the UIButton object itself:
[saveButton addTarget:target action:@selector(saveArray) forControlEvents:UIControlEventTouchUpInside];
I've tried to set target/action to the UIBarButtonItem directly but it seems not to work in case of UIButton for custom view for some reason.
OTHER TIPS
Did you remember to set the target? If the desired method belongs to the same class, you could do:
[barButton setTarget:self];
That said, action
and target
are both properties (new to Obj-C 2.0), consider using the dot notation:
barButton.action = @selector(saveArray:)
barButton.target = self;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow