views:

102

answers:

1

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?

+1  A: 

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];
Robot K
For the last line I get an error message saying "Request for member 'toolbar' is something not a structure or a union. How do I do it using self.navigationItem.rightBarButtonItem?
awakeFromNib
In that case, replace the last line with `self.navigationItem.rightBarButtonItem = barButton;`. Or you can use this method: http://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationItem_Class/Reference/UINavigationItem.html#//apple_ref/doc/uid/TP40006933-CH3-SW17.
Robot K
I tried that and nothing gets displayed.
awakeFromNib
What happens if you use the setRightBarButtonItem:animated: method?
Robot K
What's the code for that?
awakeFromNib
`[self.navigationItem setRightBarButtonItem:barButton animated:YES];`
Robot K
Yes, that worked! Not what I expected, but it shows both text and graphics.
awakeFromNib