我无法设置 UINavigationBar 标题项。我该如何设置?

I cant set the UINavigationBarTitleItem. How do I set it?

我的导航标题和代码设置有问题。

这是我的代码结构:

Navigation Controller -> TableView -> UIScreen where i want to set the title.

这是我的代码:

表视图控制器:

     import UIKit

  class ProductsTableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(UserCell.self, forCellReuseIdentifier: cellId)
}

let cellId = "cellId"
let products = [

    "Happy Face",
    "Sad Face",
    "High Five",
    "Angry Face",
    "The Earth"
]

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return products.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell

    let product = products[indexPath.row]
    cell.textLabel?.text = product

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let buyProductViewController = BuyProductViewController()
    let product = products[indexPath.row]
    buyProductViewController.nameOfItem = product

    buyProductViewController.navigationItem.title = product

    performSegue(withIdentifier: "segue", sender: self)
}
 }

  class UserCell: UITableViewCell {

 }

正在设置我的标题视图控制器:

import UIKit

class BuyProductViewController: UIViewController {

var nameOfItem: String? {

    didSet {

        print(nameOfItem)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
}

}

如果有任何人能帮助我,我将不胜感激,因为我非常沮丧并且已经为此工作了一个多星期,并且刚刚遇到堆栈溢出。

谢谢。

如果满足以下条件,这将对您有用: 1. ProductsTableViewController嵌入在UINavigationController中; 2. 标识符为 "segue" 的 Segue 是 push。请注意,不同之处在于直接设置推送控制器的标题。 NavigationBar 自动使用显示的 VC 的标题作为导航栏标题。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let buyProductViewController = BuyProductViewController()
    let product = products[indexPath.row]
    buyProductViewController.nameOfItem = product

    buyProductViewController.title = product

    performSegue(withIdentifier: "segue", sender: self)
}

请检查您是否必须在 BuyProductViewController 中设置标题:

import UIKit
class BuyProductViewController: UIViewController {
    var nameOfItem: String? {
        didSet {
            print(nameOfItem)
        }
    }

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