Define viewWillAppear from Popped UINavigationController or UITabBarController

I cannot find a way to distinguish slippage from the Nav controller stack and enter the view controller from the UITabBarController.

I want to call a method in ViewWillAppear only when the view is presented from a TabBar, and not when someone clicks back into the navigation controller.

If I did not use TabBarController, I could easily get this using the viewDidLoad function.

I tried,

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    println("View Will Appear")

    if isBeingPresented() {
        println("BP")
    }
    if isMovingFromParentViewController() {
        println("from")
    }
    if isMovingToParentViewController() {
        println("to")
    }
}

But there is no difference when I am present when I press the Tab button or when I press the return button.

Only the "View Will Appear" is called.

Using iOS 8.4 / Swift

+4
source share
3 answers

UITabBarControllerDelegate.

Bool ViewController comingFromTab:

class MyViewController: UIViewController {
    var comingFromTab = false

    // ...
}

UITabBarControllerDelegate , , shouldSelectViewController. UITabBarController .

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {

    if let myViewController = viewController as? MyViewController {
        myViewController.comingFromTab = true
}

- UINavigationController, :

if let navController = viewController as? UINavigationController {
    if let myViewController = navController.viewControllers[0] as? MyViewController {
        // do stuff
    }
}

, , viewWillAppear :

override func viewDidAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // ...
    if comingFromTab {
        // Do whatever you need to do here if coming from the tab selection
        comingFromTab = false
    }
}
+2

. , - , , viewWillAppear.

class YourViewController: UIViewController {
    var poppingBack = false

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        if !poppingBack {
            // your logic
        }
        else {
            poppingBack = false // reset it for next time
        }
    }
}

// somewhere else in code, suppose yourVC is YourViewController
yourVC.poppingBack = true
self.navigationController.popToViewController(yourVC, animated: true)

UINavigationControllerDelegate - navigationController:willShowViewController:animated: , .

+3

parentViewController

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    if parentViewController is UITabBarController {
        // Presented by UITabBarController
    } else if parentViewController is UINavigationController {
        // Presented by UINavigationController
    } else {
        // Presented by ...
    }
}
+1

Source: https://habr.com/ru/post/1598635/


All Articles