按下导航后退按钮时如何调用功能?

Leo*_*tim 4 uinavigationcontroller ios swift

当我按下后退按钮时,我需要调用一个函数.优选地,不必创建另一个按钮

Cod*_*der 10

将以下内容放在视图控制器中.

override func willMove(toParent parent: UIViewController?) {
    super.willMove(toParent: parent)

    if parent == nil {
        // The view is being removed from the stack, so call your function here
    }
}
Run Code Online (Sandbox Code Playgroud)

当parent为nil时,表示视图正从堆栈中删除(即按下后退按钮).

与matt的答案相比,其中一个考虑因素willMove是以前称之为viewWillDisappear.您的里程将根据您的功能而有所不同,但这可能会导致根据您的具体需求出现问题.话虽如此,答案完全能够满足您的要求.


mat*_*att 5

实施,viewWillDisappear并在其中进行测试isMovingFromParentViewController.如果后者是真的,那么你就会被弹出.