我有一个标题导航栏。 当我双击文本重命名它时,它实际上说它是一个导航项,所以可能是这样。

我试图改变文本使用代码,如:

declare navigation bar as navagationbar here
button stuff {
    navigationbar.text = "title"
}

这显然不是我的代码,只是展示它是如何工作的。

所以每当我按下按钮,我希望标题改变。


当前回答

在viewDidLoad

导航控制器.navigationBar.topItem ?。title = "你的文本"

其他回答

同时,如果你想手动创建导航栏,这段代码将帮助你

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);
}

如果你有一个NavigationController嵌入在一个TabBarController里面,见下面:

super.tabBarController?.title = "foobar"

您可以使用调试器脚本调试此类问题。尝试Chisel的pvc命令打印层次结构上的每个可见/隐藏视图。

在Swift 4中:

斯威夫特4

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Your title"
}

希望能有所帮助,敬礼!

这对我很管用。只需连接一个outlet到你的导航栏,并通过topItem访问标题

navBar.topItem?.title = "Your Title Here"

我更喜欢使用self. navigationitem . Title = "Your Title Here"而不是self。title = "Your title Here"在导航栏中提供标题,因为标签栏也使用self。Title来修改它的标题。您应该尝试一次下面的代码。

注意:在你做任何事情之前,调用超级视图生命周期是必要的。

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavBar()
    }
}

private func setupNavBar() {
    self.navigationItem.title = "Your Title Here"
}