Search code examples
swiftuikituinavigationbaruinavigationitem

Setting title of UINavigationbar not working


I've looked through a few online tutorials, but nothing is working.

That's the code of my viewController:

import UIKit

class ViewController: UINavigationController {

    let textView = UITextView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // tried this
        self.navigationItem.title = "AAA"

        // and this
        self.title = "AAA"

        // and finally this
        self.parent?.title = "AAA"
    }
}

I don't understand why this isn't working (I haven't used a navigation bar before)

I didn't change anything in the main.storyboard.

Thanks for your answers.


Solution

  • First of all in your storyboard select your view controller and then

    Editor -> Embed In -> Navigation Controller

    then in your ViewController class add

    self.title = "AAA"
    

    in your viewDidLoad method and your code will look like:

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.title = "AAA"
        }
    }
    

    You need to replace UINavigationController with UIViewController