Dennis van Mazijk Dennis van Mazijk - 16 days ago 5
iOS Question

Swift - Add same navigation bar items to every page

I am trying to add the same navigation bar items to every tab in my application. I currently have them set up correctly in my homeController, but I want to move the code to a separate file and remotely implement it wherever I want.

For example: adding a [search] icon to the left side of the navigation bar without having to use the same code in every swift file.

I don't know whether I should create an enum, protocol or class. What is the best way to do this?

let menuButton = UIButton(type: UIButtonType.system)
menuButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
menuButton.addTarget(self, action: #selector(openSearch), for: .touchUpInside)
menuButton.setImage(UIImage(named: "icon_search"), for: UIControlState())
let menuBarButtonItem = UIBarButtonItem(customView: menuButton)

navigationItem.leftBarButtonItems = [menuBarButtonItem]

func openSearch() {
// Some code
}

Answer

My recommended approach to this would be to create a base view controller class and make all your individual view controllers inheirit from this rather than directly from UIViewController.

Whilst you could do a quick and dirty extension as Umair suggests, this isn't practical for other applications whereas a base view controller allows you to basically add functionality/customise appearance of any aspect of all view controllers within your app.

Here is some example code:

class BaseViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let menuButton = UIButton(type: UIButtonType.system)
        menuButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
        menuButton.addTarget(self, action: #selector(openSearch), for:    .touchUpInside)
        menuButton.setImage(UIImage(named: "icon_search"), for: UIControlState())
        let menuBarButtonItem = UIBarButtonItem(customView: menuButton)

        navigationItem.leftBarButtonItems = [menuBarButtonItem
    }

    func openSearch() {

    }
}

Then for all view controllers in your app, just make the declaration:

class SomeRandomViewController: BaseViewController { }