簡體   English   中英

彈出 iOS UINavigationController 時如何調用方法?

[英]How to call a method when an iOS UINavigationController has been popped?

我有一個 iOS UINavigationController ,其rootViewControllerViewController1 ViewController1通過調用pushViewController(_:animated:)推送ViewController2 ,然后ViewController2通過調用popViewController(animated:)彈出自身。 我沒有使用 storyboard。

現在我已經回到ViewController1 ,我希望ViewController1自動執行一些操作。

當我們從ViewController2返回時,如何安排調用ViewController1的方法? 換句話說, ViewController1怎么能感覺到它剛剛被發現呢? 我知道我可以通過調用UINavigationControllerDelegatenavigationController(_:didShow:animated:)方法來做到這一點,但是有更簡單的方法嗎?

您可以創建一個協議,讓您在 ViewController2 被解除時通知 ViewController1,有點像這樣:

protocol FeedbackDelegate: class {
    func shouldDoSomething()
}

class ViewController1: UIViewController, FeedbackDelegate {
    func thisIsWhereYouPresentVC2() {
        let vc = ViewController2()
        vc.feedbackDelegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: - FeedbackDelegate
    func shouldDoSomething() {
    }
}

class ViewController2: UIViewController {
    weak var feedbackDelegate: FeedbackDelegate?
    
    func thisIsWhereYouDismissVC2() {
        self.feedbackDelegate?.shouldDoSomething()
        self.navigationController?.popViewController(animated: true)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM