将视图控制器推送到NavigationController

时间:2017-06-16 01:51:38

标签: swift uinavigationcontroller

我有一个UINavigationController,根控制器为UICollectionViewController,名为HomeController,我已经在我的AppDelegate中设置了:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()

        let layout = UICollectionViewFlowLayout()
        window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))    
        return true
    }
    ...
}

现在在我的HomeController中,我试图设置一个新的ViewControllerdummySettingViewController)的中心文本,我将其推送到NavigationController,如下所示:

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    ...
    func showControllerForSettings(setting: SettingModel) {
        let dummySettingViewController = UIViewController()
        dummySettingViewController.view.backgroundColor = UIColor.white
        navigationController?.pushViewController(dummySettingViewController, animated: true)
        //THIS DOESN'T SET THE dummySettingViewController TITLE TEXT
        self.navigationItem.title = "TEST_TITLE"
        navigationController?.navigationBar.tintColor = UIColor.white
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

    }
    ...
}

我的问题出在这一行self.navigationItem.title = "TEST_TITLE"。它没有设置推送到dummySettingViewController的新navigationController的中心标题文字,而是设置back button NavBar中的dummySettingViewController文字} TEST_TITLE

在这一行中:self.navigationItem.title = "TEST_TITLE"当我使用self时指的是HomeViewController navigationItem或NavBar的{​​{1}}?我对每个navigationController的{​​{1}}如何运作感到困惑?有人可以澄清一下吗?

1 个答案:

答案 0 :(得分:4)

  

我的问题在于此行self.navigationItem.title =“TEST_TITLE”。它没有设置推送到navigationController的新dummySettingViewController的中心标题文本,而是将dummySettingViewController的NavBar中的后退按钮文本设置为TEST_TITLE。

这正是它所期望的。将视图控制器推入导航控制器时,该视图控制器的导航项将被推送到导航栏。然后将之前的视图控制器的导航项标题用作当前视图控制器的后退按钮的标题,这是您观察到的。您需要在dummySettingViewController的导航项上设置“TEST_TITLE”,而不是self的(即上一个视图控制器)项目。