Search code examples
iosswiftuitoolbar

Add custom toolbar to every view in swift using navigation bar or creating custom class?


I want a toolbar added to every view of my application that is very basic and looks like this: enter image description here

Note: the left and right item will be the same in every view.

I am wondering if it would be better to customize the navigation bar in every viewcontroller or to create a class that extends the UIToolBar and add that to every controller. What would be better practice?


Solution

  • According to me you should create an extension of UIViewController. It'll have a method which will contain the code to modify the navigation bar for that view controller. This way you can modify the navigation bar for the required screen and it will be highly flexible design wise.

    For example below extension will set the navigation bar to transparent,

    extension UIViewController {
    
    func setTransparentNavBar(_ target: UIViewController, leftAcion: Selector, rightAction: Selector) {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.isTranslucent = true
    
        self.navigationItem.titleView = UIImageView(image: UIImage(named: "icon_2"))
    
        let leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_1"), style: UIBarButtonItem.Style.plain, target: target, action: leftAcion)
        //self.navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
        self.navigationItem.leftBarButtonItem = leftBarButtonItem
    
        let rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_3"), style: UIBarButtonItem.Style.plain, target: target, action: rightAction)
        //self.navigationItem.setRightBarButton(rightBarButtonItem, animated: true)
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
    }
    

    }

    Whenever this configuration is required call this method in viewDidLoad()

    Hope this helps.