Search code examples
objective-ciosuibarbuttonitemuiappearance

customize uibarbuttonitem without uiappearance


Is there a way to customize ALL uibarbuttonitems to have a background image without using UIApperance? Unfortunately our codebase has some limitations and we're not able to use UIAppearance so I'm looking for an alternative.

Thanks in advance.

Edit: I was able to do this by subclassing UIBarButtonItem and it works for most of my buttons...but I'm wondering specifically how to do it with default buttons like UITableView edit buttons and UINavigationController backbuttons.

Thanks!


Solution

  • You also can make subclass like this. First i go to make subclass of UIBarButtonItem. My CustomBarButtonItem.h should be like this.

    @interface CustomBarButtonItem : UIBarButtonItem
    
    + (CustomBarButtonItem *)sharedInstance;
    - (UIBarButtonItem *)backButtonwithTarget:(id)target andAction:(SEL)action;
    
    
    @end
    

    then inside my CustomBarButtonItem.m should like this.

    @implementation CustomBarButtonItem
    
    static CustomBarButtonItem * _sharedInstance = nil;
    
    + (CustomBarButtonItem *)sharedInstance
    {
        if (_sharedInstance != nil)
        {
            return _sharedInstance;
        }
        _sharedInstance = [[CustomBarButtonItem alloc] init];
    
        return _sharedInstance;
    }
    
    - (UIBarButtonItem *)backButtonwithTarget:(id)target andAction:(SEL)action
    {
        UIImage *backImage = [UIImage imageNamed:@"back_btn_normal.png"];
        UIImage *backPressed = [UIImage imageNamed:@"back_btn_hilight.png"];
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
        [backButton setBackgroundImage:backPressed forState:UIControlStateHighlighted];
    
        const CGFloat BarButtonOffset = 5.0f;
        [backButton setFrame:CGRectMake(BarButtonOffset, 0, backImage.size.width, backImage.size.height)];
    
        UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backImage.size.width, backImage.size.height)];
        [containerView addSubview:backButton];
    
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:containerView];
        return item;
    }
    @end
    

    Then where ever you want to make custom NavigationItem (Button in the NavigationBar) you can put the code below for me it custom.

    - (void)viewDidLoad
    {
        self.navigationItem.leftBarButtonItem = [[CustomBarButtonItem sharedInstance] backButtonwithTarget:self andAction:@selector(searchButtonTapped:)];
    }
    

    All of my code are working fine. Hopefully it will help you.