objective-ccocoa-touchuibarbuttonitem

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


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?


Solution

  • 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];