从Popped UINavigationController或UITabBarController

时间:2015-07-20 02:06:27

标签: ios swift uinavigationcontroller uitabbarcontroller viewwillappear

我无法找到区分从Nav控制器堆栈弹出和从UITabBarController进入视图控制器的方法。

我想在ViewBillAppear中调用一个方法,只有当视图从TabBar中显示时,而不是当有人按下导航控制器时。

如果我没有使用TabBarController,我可以使用viewDidLoad轻松实现此功能。

我试过了,

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

    println("View Will Appear")

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

但是当我按下Tab键按钮或按下后退按钮时,没有任何区别。

只有“View Will Appear”才会被调用。

使用iOS 8.4 / Swift

3 个答案:

答案 0 :(得分:4)

没有办法确定。所以我想最简单的方法是添加一些你必须更改的变量,然后再回到那个视图控制器并在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:方法,并检查从标签栏显示视图控制器时是否会调用它。

答案 1 :(得分:2)

听起来好用UITabBarControllerDelegate

首先,在ViewController Bool上添加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 :(得分:1)

您可以查看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 ...
    }
}