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

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

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

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

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


当前回答

斯威夫特5.1

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "What ever you want"
}

其他回答

我更喜欢使用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"
}

如果你有一个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"

对于使用swift4的人来说,正确答案是

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