How can I have a UIBarButtonItem with both image and text?

node ninja picture node ninja · Oct 11, 2010 · Viewed 31.4k times · Source

When I try to use an image for a UIBarButtonItem, the text isn't shown. Is there a way to show both the text and the image?

Answer

Kris Markel picture Kris Markel · Oct 11, 2010

You can init the UIBarButtonItem with a custom view that has both image and text. Here's a sample that uses a UIButton.

UIImage *chatImage = [UIImage imageNamed:@"08-chat.png"];

UIButton *chatButton = [UIButton buttonWithType:UIButtonTypeCustom];
[chatButton setBackgroundImage:chatImage forState:UIControlStateNormal];
[chatButton setTitle:@"Chat" forState:UIControlStateNormal];
chatButton.frame = (CGRect) {
    .size.width = 100,
    .size.height = 30,
};

UIBarButtonItem *barButton= [[[UIBarButtonItem alloc] initWithCustomView:chatButton] autorelease];
self.toolbar.items = [NSArray arrayWithObject:barButton];