Search code examples
iosswiftuinavigationcontrollerswift2

Set image and title for bar button item?


I currently have a custom navigation controller with bar button items that are simply text buttons. Is it possible to keep the title of the bar button items but also set them as images (icon image + title underneath).

class NavigationController: UINavigationController
{
    var mode: NavigationMode = .Swipe {
        didSet {
            self.setButtonAttributes()
        }
    }

    private var leftBarButton: UIBarButtonItem!
    private var middleBarButton: UIBarButtonItem!
    private var rightBarButton: UIBarButtonItem!
    private var rightBarButton2: UIBarButtonItem!

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    func configureNavigationItem(navigationItem: UINavigationItem)
    {
        //Configure the bar buttons text and actions


        if (self.leftBarButton == nil) {
            self.leftBarButton = UIBarButtonItem(title: "Menu1", style: .Plain,target: self, action: "menu1Pressed:")
        }
        if (self.middleBarButton == nil) {
            self.middleBarButton = UIBarButtonItem(title: "Games", style: .Plain, target: self, action: "gamesPressed:")
        }
        if (self.rightBarButton == nil) {
            self.rightBarButton = UIBarButtonItem(title: "Menu3", style: .Plain, target: self, action: "menu3Pressed:")
        }
        if (self.rightBarButton2 == nil) {
            self.rightBarButton2 = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: "settingsPressed:")
        }

        self.setButtonAttributes()

        navigationItem.leftBarButtonItems = [self.leftBarButton, self.middleBarButton, self.rightBarButton, self.rightBarButton2]

    }

Updated:

  let button = UIButton(type: .System)
        button.setImage(UIImage(named: "play"), forState: .Normal)
        button.setTitle("Play", forState: .Normal)
        button.sizeToFit()

        leftBarButton = UIBarButtonItem(customView: button)

        if (self.leftBarButton == nil) {
            self.leftBarButton = UIBarButtonItem(title: "Play", style: .Plain,target: self, action: "Pressed:")
        }

Solution

  • 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() {
    
    }