UIBarButtonItem with UIButton as CustomView - from UIButton, how to access the UIBarButtonItem its in?

前端 未结 5 744
误落风尘
误落风尘 2021-01-05 06:51

I have a UIBarButtonItem with UIButton as custom view.

The UIButton has a addTarget:action: on it. In the action

5条回答
  •  星月不相逢
    2021-01-05 07:42

    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:

    1. Subclass a UIButton
    2. Create within it a property of type UIBarButtonItem (a weak one to avoid retaincycle)
    3. Inject the bar button item in the UIButton when you create it.

    Maybe it could work, but I will prefer the first one.

提交回复
热议问题