Search code examples
iosswiftcosmicmind

How do I update the Toolbar Buttons


I am using this phenomenal framework and had difficulties updating buttons on the toolbar. I followed the sample code of the NavigationDrawerController. So initially, the toolbar is populated with a menuButton on the left side and two other buttons on the right side:

// From AppToolbarController.swift
fileprivate func prepareToolbar() {
    toolbar.leftViews = [menuButton]
    toolbar.rightViews = [switchControl, moreButton]
}

Now, when I want to change the buttons in the toolbar from another ViewController, I (naive as I am) do the following:

// From RootViewController.swift
fileprivate func prepareToolbar() {
    guard let tc = toolbarController else {
        return
    }

    tc.toolbar.rightViews = [someOtherButton]
}

However, this has no effect and the buttons remain unchanged. This method only works for me when toolbar.rightViews was not set before.

What is the proper way to update the toolbar buttons?


Solution

  • I think the issue might be that you are calling the update Toolbar (prepareToolbar) function from the viewDidLoad function. The issue will be that the RootViewController is not actually connected to the toolbarController. Try moving the prepareToolbar function to the viewWillAppear function of the view controller. If this does not help, can you show the code setup? All the best!

    Code Sample:

    class RootViewController: UIViewController {
        fileprivate var remindersButton: IconButton!
    
        open override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = Color.white
        }
    
        open override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            prepareRemindersButton()
            prepareToolbar()
        }
    }
    
    extension RootViewController {
        fileprivate func prepareRemindersButton() {
            remindersButton = IconButton(image: Icon.cm.bell, tintColor: .white)
            remindersButton.pulseColor = .white
        }
    
        fileprivate func prepareToolbar() {
            guard let toolbar = toolbarController?.toolbar else {
                return
            }
    
            toolbar.title = "Material"
            toolbar.titleLabel.textColor = .white
            toolbar.titleLabel.textAlignment = .left
    
            toolbar.detail = "Build Beautiful Software"
            toolbar.detailLabel.textColor = .white
            toolbar.detailLabel.textAlignment = .left
    
            toolbar.rightViews = [remindersButton]
        }
    }