2014-10-17 36 views
3

如何設置動作backBarButtonItem並仍然顯示左箭頭?如何在swift中設置動作backBarButtonItem?

我用這個代碼,但箭不顯示

var barBack = UIBarButtonItem(title: "Reset", style: UIBarButtonItemStyle.Plain, target: self, action: "reset:") 
self.navigationItem.leftBarButtonItem = barBack 

,但是當我用這個代碼的動作不靈

self.navigationController?.navigationBar.topItem?.backBarButtonItem = barBack 

感謝

回答

0

試試這個

var barBack = UIBarButtonItem(title: "Reset", style: UIBarButtonItemStyle.Plain, target: self, action: "reset:") 
self.navigationItem.leftBarButtonItem = barBack 

讓我知道它是否有效。

+0

這看起來像我的代碼。請仔細閱讀我的問題。謝謝 – 2014-10-19 04:06:42

+0

事實上,它有點不同,因爲您正在使用導航控制器的導航欄的頂部項目屬性,可能並不總是處於活動狀態,例如頁面未嵌入導航控制器中時。另一方面,我使用頁面的navigationItem的leftBarButtonItem。請嘗試我的代碼,看看它是否工作,因爲我在發佈答案之前嘗試過它 – 2014-10-19 14:18:13

+0

我們的代碼之間唯一常見的事情是barbuttonitem的初始化 – 2014-10-19 14:18:39

2

作爲設置操作的替代方法,您可以保留backBarButtonItem並使用isMovingFromParentViewController代替處理在導航堆棧上移回的邏輯。

override func viewWillDisappear(animated: Bool) { 
    super.viewWillDisappear(animated) 
    if isMovingFromParentViewController() { 
     .. do something here 
    } 
} 
0

試試這個: 在ViewDidLoad

let backButton = UIBarButtonItem(title: "< Home", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack") 
    navigationItem.leftBarButtonItem = backButton 
    navigationItem.backBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "the_font_you_want_to_use", size: size_of_the_font_this_should_be_integer)!], forState: UIControlState.Normal) 

,並實現以下方法:

func goBack() { 
    self.navigationController?.popToRootViewControllerAnimated(boolean) 
} 

只需更換the_font_you_want_to_use,size_of_the_font_this_should_be_integer和你想要的布爾值,一切都將正在工作。

***編輯

如果你不想回去Root View Controller,而不是

self.navigationController?.popToRootViewControllerAnimated(boolean) 

你可以說:

self.navigationController?.popViewControllerAnimated(boolean) 

甚至流行到一些其他的ViewController,指定popToViewController的第一個參數爲YourViewController類的對象,第二個爲動畫的布爾值。

相關問題