Changing navigation title programmatically

后端 未结 14 2182
长情又很酷
长情又很酷 2020-11-28 19:34

I have a navigation bar with a title. When I double click the text to rename it, it actually says it\'s a navigation item, so it might be that.

I\'m trying to change

相关标签:
14条回答
  • 2020-11-28 19:39

    Try the following in viewDidLoad

    self.navigationItem.title = "Your Title"
    
    0 讨论(0)
  • 2020-11-28 19:41

    If you have a NavigationController embedded inside of a TabBarController see below:

    super.tabBarController?.title = "foobar"
    

    You can debug issues like this with debugger scripts. Try Chisel's pvc command to print every visible / hidden view on the hierarchy.

    0 讨论(0)
  • 2020-11-28 19:43

    You change the title by changing the title of the view controller being displayed:

    viewController.title = "some title"
    

    Normally this is done in view did load on the view controller:

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "some title"
    }
    

    However, this only works if you have your view controller embedded in a UINavigationController. I highly recommend doing this instead of creating a navigation bar yourself. If you insist on creating a navigation bar yourself, you can change the title by doing:

    navigationBar.topItem.title = "some title"
    
    0 讨论(0)
  • 2020-11-28 19:48

    Swift 5.1

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "What ever you want"
    }
    
    0 讨论(0)
  • 2020-11-28 19:50

    The code below works for me with Xcode 7:

    override func viewDidLoad() {        
        super.viewDidLoad()
        self.navigationItem.title = "Your Title"
    }
    
    0 讨论(0)
  • 2020-11-28 19:50

    I prefer using self.navigationItem.title = "Your Title Here" over self.title = "Your Title Here" to provide title in the navigation bar since tab bar also uses self.title to alter its title. You should try the following code once.

    Note: calling the super view lifecycle is necessary before you do any stuffs.

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            setupNavBar()
        }
    }
    
    private func setupNavBar() {
        self.navigationItem.title = "Your Title Here"
    }
    
    0 讨论(0)
提交回复
热议问题