Last Updated: February 25, 2016
·
970
· kerrishotts

Quick & Easy UIBarButtonItem Creation Utility

So this tip isn't anything earth-shattering, but I found myself needing to create a lot of UIBarButtonItems using FontAwesome (and regular text) with specific text attributes and a blank background. Rather than repeat myself several times in code, I just created a simple UIBarButtonItem category to do the hard work for me.

To create a simple UIBarButtonItem using a specific FontAwesome icon, you can do this, using the category:

NSDictionary *faTextAttributes = 
    @{ UITextAttributeFont : [UIFont fontWithName: 
        kFontAwesomeFamilyName size: 22],
        UITextAttributeTextColor : [UIColor whiteColor],
        UITextAttributeTextShadowColor: 
            [UIColor blackColor],
        UITextAttributeTextShadowOffset: 
            [NSValue valueWithCGSize:  CGSizeMake(0,-1)] 
    };

UIImage *blankImage = [UIImage new];

UIBarButtonItem *aMenuButton = 
    [UIBarButtonItem barButtonItemUsingFontAwesomeIcon:
    @"icon-reorder" 
    target:self action:@selector(showMenu:) 
    withTitleTextAttributes:faTextAttributes 
    andBackgroundImage:blankImage];

So, for one UIBarButtonItem it isn't going to save any time, but I had lots to build in code. I also had a couple of items specific to the app that needed to be added to every UIBarButtonItem created in this manner, and so I also added them to the category. It definitely saved time and typing by having the utility create it for me. (Note: I've left out the custom parts in the gist.)

Using text-only UIBarButtonItems is virtually identical -- just have a Text Attribute Dictionary with a regular font and use barButtonItemWithTitle:target:action:withTitleTextAttributes:andBackgroundImage:].

The entire gist is at https://gist.github.com/kerrishotts/4980294, and under a MIT license.