Set image and title for bar button item?

Solution 1:

You can create UIButton instance, set an image and a title for it, and then create your UIBarButtonItem with it:

    let button = UIButton(type: .System)
    button.setImage(UIImage(named: "YourImage"), forState: .Normal)
    button.setTitle("YourTitle", forState: .Normal)
    button.sizeToFit()
    self.leftBarButton = UIBarButtonItem(customView: button)

To add an action:

    button.addTarget(self, action: #selector(self.someAction), forControlEvents: .TouchUpInside)

where self.someAction is

func someAction() {

}

Solution 2:

Create an UIButton, set an image and a title for it and use it as a custom image to init your UIBarButtonItem(customView:) with it.

If you want the image to be on the right side of the button, you can set the button's semanticContentAttribute to .forceRightToLeft.

Swift 4 example:

let view = UIView()
let button = UIButton(type: .system)
button.semanticContentAttribute = .forceRightToLeft
button.setImage(UIImage(named: "DocumentsIcon"), for: .normal)
button.setTitle("Documents", for: .normal)
button.addTarget(self, action: #selector(openDocuments), for: .touchUpInside)
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)

Solution 3:

Swift 3:

    let button = UIButton(type: .system)
    button.setImage(UIImage(named: "categories_icon"), for: .normal)
    button.setTitle("Categories", for: .normal)
    button.addTarget(self, action: #selector(showCategories), for: .touchUpInside)
    button.sizeToFit()
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)