I have a UIBarButtonItem
with UIButton
as custom view.
The UIButton
has a addTarget:action:
on it. In the action
First of all, why do you need to access the UIBarButtonItem
?
Then, to create a UIBarButtonItem
with a custom view I suggest you to create a category extension like the following (in this case the custom view is a UIButton
).
//UIBarButtonItem+Extension.h
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image title:(NSString*)title target:(id)target action:(SEL)action;
//UIBarButtonItem+Extension.m
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image title:(NSString*)title target:(id)target action:(SEL)action
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
return [barButtonItem autorelease];
}
and the use it like this (first import UIBarButtonItem+Extension.h
):
UIBarButtonItem* backBarButtonItem = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"YoutImageName"] title:@"YourTitle" target:self action:@selector(doSomething:)];
where the selector it's a method that is implemented inside the class (the target) that uses that bar button item.
Now inside the doSomething:
selector you could the following:
- (void)doSomething:(id)sender
UIButton* senderButton = (UIButton*)sender;
[popover presentPopoverFromRect:senderButton.bounds inView:senderButton...];
}
A category in this case it's useful to not duplicate code. Hope it helps.
P.S. I'm not using ARC but same considerations can be also applied.
Edit:
An easy solution to access the bar button item could be the following:
UIButton
UIBarButtonItem
(a weak one to avoid retaincycle)UIButton
when you create it.Maybe it could work, but I will prefer the first one.