Changing navigation title programmatically

后端 未结 14 2184
长情又很酷
长情又很酷 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:55

    If you wanted to change the title from a child view controller of a Page View Controller that's embedded in a navigation controller, it would look like this:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.parent?.title = "some title"
    }
    
    0 讨论(0)
  • 2020-11-28 19:56

    The correct answer for people using swift4 would be

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

    In Swift 4:

    Swift 4

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

    I hope it helps, regards!

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

    Normally, the best-practice is to set the title on the UIViewController. By doing this, the UINavigationItem is also set. Generally, this is better than programmatically allocating and initializing a UINavigationBar that's not linked to anything.

    You miss out on some of the benefits and functionality that the UINavigationBar was designed for. Here is a link to the documentation that may help you. It discusses the different properties you can set on the actual bar and on a UINavigationItem.

    Just keep in mind:

    1. You lose back button functionality (unless you wire it yourself)
    2. The built-in "drag from the left-hand side to swipe back" gesture is forfeited

    UINavigationController's are your friends.

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

    and also if you will try to create Navigation Bar manually this code will help you

    func setNavBarToTheView() {
        let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64.0))
        self.view.addSubview(navBar);
        let navItem = UINavigationItem(title: "Camera");
        let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(CameraViewController.onClickBack));
        navItem.leftBarButtonItem = doneItem;
        navBar.setItems([navItem], animated: true);
    }
    
    0 讨论(0)
  • 2020-11-28 20:05

    I found this to work:

    navigationItem.title = "Title"
    
    0 讨论(0)
提交回复
热议问题