bibscy
bibscy

Reputation: 2708

Were to call method to change appearance of navigation bar? Swift 3

I have several viewcontrollers embedded in a UINavigationController. I would like to customize the appearance of the Navigation Bar title for each viewController. What is the best method where to call setCustomTitleInNavBar. If it is called in viewDidLoad, self is not yet initialized and the app will crash. In ViewWillAppear title is not yet displayed when view is shown to user. Please advise alternative implementation if this is not the correct way to do it.

class CustomMethods {
  func setCustomTitleInNavBar(textValue:String, VC:UIViewController) -> UIView {
     let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
     titleLabel.text = textValue
     titleLabel.adjustsFontSizeToFitWidth = true
     titleLabel.textAlignment = NSTextAlignment.center
       VC.navigationItem.titleView = titleLabel
           return VC.navigationItem.titleView!
  }
}


//call method on the current view controller to modify the nav bar title
   class someViewController: UIViewController {
     override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(true)  
         setCustomTitleInNavBar(textValue: "Where to come?", VC: self)
  }
}

Upvotes: 1

Views: 1027

Answers (2)

BoilingLime
BoilingLime

Reputation: 2267

Here is a way to implement it through protocol :

// Protocol
protocol NavigationBarSetUpProtocol: class {

    // Add more param if needed
    func setupNavigationBar(with title: String)
}

// Default implemention
extension NavigationBarSetUpProtocol where Self: UIViewController {

    // Default implementation
    func setupNavigationBar(with title: String) {

        // configure you VC navigation item with : self.navigationItem.titleView = ...
    }

}

// VC A
class ViewControllerA: UIViewController, NavigationBarSetUpProtocol {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar(with: "HOME")
    }

}

// VC B
class ViewControllerB: UIViewController, NavigationBarSetUpProtocol {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar(with: "PROFILE")
    }

}

Upvotes: 2

pesch
pesch

Reputation: 1996

You can call

navigationItem.title = "Your title"

in viewDidLoad.

Upvotes: 1

Related Questions