标题有什么不同?

What's the different with titles?

我想为我的 UIViewController 添加标题:

我试过了

self.navigationController.navigationItem.title
self.navigationController.title
self.title

有时解决方案 1 有效,有时解决方案 2 有效,有时解决方案 3 有效。

哪位高手能告诉我它们的区别吗?

titleUIViewController 的 属性。

A localized string that represents the view this controller manages. Set the title to a human-readable string that describes the view. If the view controller has a valid navigation item or tab-bar item, assigning a value to this property updates the title text in those objects.


self.navigationController 是一个 UINavigationController,用于管理您的 viewController 所在的视图控制器堆栈。UINavigationControllerUIViewController 的子类,因此 self.navigationController.titleUINavigationControllertitle


self.navigationItem.title:

The navigation item’s title displayed in the center of the navigation bar. The default value is nil. When the receiver is on the navigation item stack and is second from the top—in other words, its view controller manages the views that the user would navigate back to—the value in this property is used for the back button on the top-most navigation bar. If the value of this property is nil, the system uses the string “Back” as the text of the back button.


因此,在实践中,您应该设置 ViewControllertitle。如果您的 ViewControllerUINavigationController,当您按下另一个 ViewController 时,它会将该文本用于 后退按钮 ,如果您的 ViewController 被管理,它将显示在标签栏中通过 UITabBarController.

我创建一个演示来解释它们:

你看,我的vc1是黄灰色的color嵌入了一个navigation controller,我的vc2是浅绿色的color嵌入了一个navigation controller也是,两个navigation controller都是由一个tabbar controller管理的。

ViewController.swift中(就是vc1),如果我设置self.title

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "vc1's title"  
    }

}

ViewController2.swift中(即vc2):

import UIKit

class ViewController2: UIViewController {

       override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "vc2's title"
    }

}

结果是 tabbar titlenavigation title 全部设置:

如果我设置self.navigationController?.title:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // self.title = "vc1's title"

        self.navigationController?.title = "vc1's nav title"

    }
}

结果是tabbar title设置:

如果我设置self.navigationItem.title:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // self.title = "vc1's title"

        //self.navigationController?.title = "vc1's nav title"

        self.navigationItem.title = "vc1's navItem title"
    }
}

结果是navigation title设置: