从 TableView 推送视图控制器后如何保持导航栏标题大

dan*_*fin 6 xcode uitableview uiviewcontroller ios swift

I have a tableview displaying on a main view controller, and when a row is selected a detail view controller is pushed. 我有一个主视图控制器的大标题,以及详细视图控制器的小/常规标题。它们嵌入在导航控制器和标签栏控制器中。

Before selecting a row, the main view controller title is large, and when a row is selected the detail view controller title is regular as it should be. 但是,当我从详细视图控制器(通过“后退”按钮)返回主视图控制器时,主视图控制器上的标题不再大。

我在主视图控制器上将“prefersLargeTitles”设置为true,在详细视图控制器上将“largeTitleDisplayMode”设置为从不。

我曾尝试将“largeTitleDisplayMode”设置为始终在主视图控制器上,但无济于事。我还尝试在任一视图控制器上将其设置为自动,但似乎没有效果。

我还尝试使用“viewWillAppear”和“viewWillDisappear”并在那里设置标题,虽然它确实将主视图控制器标题重置回大,但动画滞后并且不像通常那样平滑小标题到大标题。

此外,我对编码还很陌生,这是我在不使用故事板的情况下构建的第一个应用程序,因此代码可能会一团糟。

主视图控制器代码:

class HomeViewController: UIViewController {

  let tableView = UITableView()

  override func loadView() {
      super.loadView()
      view.backgroundColor = .white
      self.title = "Home"

      // Set large title
      navigationController?.navigationBar.prefersLargeTitles = true


      // Make navigation bar transparent
      navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
      navigationController?.navigationBar.shadowImage = UIImage()
      navigationController?.navigationBar.isTranslucent = true


}


extension HomeViewController: UITableViewDelegate {

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

      let vc = DetailViewController() as DetailViewController

      if indexPath.section == 0 {
          vc.detailTitle = itemsTop[indexPath.row]
      } else if indexPath.section == 1 {
          vc.detailTitle = itemsBottom[indexPath.row]
      } else {
          print("Failed to load title")
      }


      navigationController?.pushViewController(vc, animated: true)

      tableView.deselectRow(at: indexPath, animated: true)
  }

}
Run Code Online (Sandbox Code Playgroud)

详细视图控制器代码:

class DetailViewController: UIViewController {

  var detailTitle: String?

  override func viewDidLoad() {
      super.viewDidLoad()

      title = detailTitle

      // Make nav bar transparent
      navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
      navigationController?.navigationBar.shadowImage = UIImage()
      navigationController?.navigationBar.isTranslucent = true

      // Prevent large title
      navigationController?.navigationBar.prefersLargeTitles = false
  }

}
Run Code Online (Sandbox Code Playgroud)

Sam*_*ikh 8

试试这个它有效。在“HomeViewController”中

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.prefersLargeTitles = true
}
Run Code Online (Sandbox Code Playgroud)

在“详细视图控制器”中

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.largeTitleDisplayMode = .never
}
Run Code Online (Sandbox Code Playgroud)