2016-07-27 23 views
0

我需要在textField中寫入某些內容,並且在鍵盤上按回車時會更改我的導航欄中的全局標題(對於整個應用程序)。如何用代表更改全局導航欄標題?

我已經被要求與代表一起執行這個動作,但是我沒有找到來自navigationController的任何委託方法來執行此操作。

+1

你將不得不設置每個視圖控制器的標題在他們的viewDidLoad或同等 – Luke

+0

我需要與導航欄代表執行它 – JoseMartinFit

回答

0

是的,你可以成功,但你必須在每個推/呈現視圖控制器中處理。最好的方法是繼承導航控制器並在推送/呈現視圖控制器時覆蓋標題。

自定義導航控制器: enter image description here

Swift代碼:

class MyNavigationController: UINavigationController, UINavigationBarDelegate { 

    var navFixedTitle: String? 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { 
     super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) 
    } 

    override func pushViewController(viewController: UIViewController, animated: Bool) { 
     viewController.title = navFixedTitle ?? "Constant" 
     super.pushViewController(viewController, animated: animated) 
    } 

    //Nav Bar Delegate 
    func navigationBar(navigationBar: UINavigationBar, didPushItem item: UINavigationItem) { 
//  navigationBar.backItem?.title = "Back" 
    } 
} 

設置你的標題:我使用表格視圖

,在不同的細胞敲擊時導航標題將相應設置。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    if let nav = self.navigationController as? MyNavigationController { 
     nav.navFixedTitle = sec1[indexPath.row] 
    } 
    performSegueWithIdentifier("push", sender: tableView.cellForRowAtIndexPath(indexPath)) 
} 

輸出:

enter image description here