2017-02-14 52 views
1

我想在導航堆棧中出現的每個視圖控制器上都有一個關閉按鈕。我讀過here,我需要創建一個對象是一個uinavigationdelegate,我認爲這個對象將有一個像didTapCloseButton一樣的方法?爲uinavigationcontroller堆棧上的每個視圖控制器創建關閉按鈕

問題: 我應該創建一個協議,讓一切確認它,即:

protocol CustomDelegate: UINavigationControllerDelegate { 
    func didTapCloseButton() 
} 

public class ViewController: CustomDelegate { 
    func didTapCloseButton() { 
    //not sure what goes in here? 
    } 
} 

我如何關閉按鈕顯示在每個視圖的導航欄? 當用戶點擊關閉按鈕時,如何解除堆棧中的所有視圖?

感謝您的幫助!

+0

我相信你可能是這裏混淆了,實際上有Apple實施的UINavigationControllerDelegate [1]協議。 [1]:https://developer.apple.com/reference/uikit/uinavigationcontrollerdelegate – ff10

+0

權利讓我編輯我的帖子,以便我創建一個從UINavigationDelegate繼承的自定義委託。 – Number45

回答

0

這裏有一個簡單的解決方案。創建UINavigationController子類並覆蓋pushViewController方法。

class NavigationController: UINavigationController { 
    override func pushViewController(_ viewController: UIViewController, animated: Bool) { 
     super.pushViewController(viewController, animated: animated) 

     let closeBarButtonItem = UIBarButtonItem(
      title: "Close", 
      style: .done, 
      target: self, 
      action: #selector(self.popViewController(animated:))) 

     viewController.navigationItem.rightBarButtonItem = closeBarButtonItem 
    } 
} 
0

不知道這是否是您的本意,但你可以這樣做:

protocol CustomDelegate: UINavigationControllerDelegate { 
    func didTapCloseButton() 
} 
extension CustomDelegate where Self : UIViewController{ 
    func didTapCloseButton(){ 
     // write your default implementation for all classes 
    } 

} 

現在每UIViewController類,你有你可以這樣做:

class someViewController: CustomDelegate{ 

    @IBAction buttonClicked (sender: UIButton){ 
    didTapCloseButton() 
    } 
} 
相關問題