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
2010-10-11 03:26:26
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
2010-10-11 03:30:21
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
2010-10-11 03:39:55
I tried that and nothing gets displayed.
awakeFromNib
2010-10-11 03:41:26
What happens if you use the setRightBarButtonItem:animated: method?
Robot K
2010-10-11 03:44:30
What's the code for that?
awakeFromNib
2010-10-11 05:00:52
`[self.navigationItem setRightBarButtonItem:barButton animated:YES];`
Robot K
2010-10-11 06:04:42
Yes, that worked! Not what I expected, but it shows both text and graphics.
awakeFromNib
2010-10-11 10:04:13