Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
node ninja Avatar asked Oct 11 '10 01:10

node ninja


3 Answers

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];
like image 107
Kris Markel Avatar answered Nov 09 '22 03:11

Kris Markel


I suggest a way how to do this using Storyboard:

  1. Drag and drop to ToolBar usual UIView. It automatically will be wrapped to Bar Button Item. Adjust View width in "Size inspector". Change background color of View to clear color.

enter image description here

  1. Put UIButton and UILabel inside a View. You can use constraints to adjust their positions. Also you can put thier outside of a View, for example, little higher or less (like on my picture). Put Default and Highlighted images for UIButton.

  2. Copy Bar Button Item and adjust another buttons. Add Flexible spaces.

  3. Create outlets.

  4. Done :). When you run app, you get Tool Bar like this:

enter image description here

P.S. Here you can read how to create UIToolbar subclass using .xib

like image 30
Igor Avatar answered Nov 09 '22 03:11

Igor


Swift 4.2 with target

extension UIBarButtonItem {
    convenience init(image :UIImage, title :String, target: Any?, action: Selector?) {
        let button = UIButton(type: .custom)
        button.setImage(image, for: .normal)
        button.setTitle(title, for: .normal)
        button.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)

        if let target = target, let action = action {
            button.addTarget(target, action: action, for: .touchUpInside)
        }

        self.init(customView: button)
    }
}
like image 37
abbood Avatar answered Nov 09 '22 02:11

abbood