问题描述
我无法找到一种方法来区分是从Nav控制器堆栈弹出还是从UITabBarController进入视图控制器.
I am unable to find a way to distinguish between popping from the Nav controller stack and entering the view controller from the UITabBarController.
我只想在从TabBar呈现视图时才调用ViewWillAppear中的方法,而不是在有人向后按导航控制器时调用它.
I want to call a method in ViewWillAppear only when the view is presented from the TabBar, not when someone presses back in the navigation controller.
如果我不使用TabBarController,则可以使用viewDidLoad轻松获得此功能.
If I wasn't using a TabBarController, I could easily get this functionally using 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键或按向后按钮没有区别.
But there is no difference when I present from pressing the Tab Button or when press back button.
只有视图将出现"被调用.
Only the "View Will Appear" is getting called.
使用iOS 8.4/Swift
Using iOS 8.4 / Swift
推荐答案
听起来很像 UITabBarControllerDelegate
.
Sounds like a good use of the UITabBarControllerDelegate
.
首先,在ViewController comingFromTab
上添加Bool
属性:
First, add a Bool
property on your ViewController comingFromTab
:
class MyViewController: UIViewController {
var comingFromTab = false
// ...
}
将UITabBarControllerDelegate
设置为所需的任何类,并实现方法shouldSelectViewController
.您可能还想继承UITabBarController的子类,然后将它们放在其中.
Set your UITabBarControllerDelegate
to whatever class you want and implement the method shouldSelectViewController
. You may also want to subclass UITabBarController and put them in there.
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
if let myViewController = viewController as? MyViewController {
myViewController.comingFromTab = true
}
如果标签的初始视图控制器是UINavigationController
,则必须将其解开并访问它的第一个视图控制器:
If your tab's initial view controller is a UINavigationController
, you will have to unwrap that and access it's first view controller:
if let navController = viewController as? UINavigationController {
if let myViewController = navController.viewControllers[0] as? MyViewController {
// do stuff
}
}
最后,在视图控制器的viewWillAppear
中添加所需的任何功能:
Lastly, add whatever functionality you need in viewWillAppear
in your view controller:
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
}
}
这篇关于从弹出的UINavigationController或UITabBarController确定viewWillAppear的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!