ios - 检测 View Controller 何时可见

标签 ios swift uinavigationcontroller viewcontroller uinavigationitem

情况

假设我在导航 Controller 中有 2 个 View Controller 。在 Storyboard中,它们看起来像:

NC -> VC1 -> VC2

NC:导航 Controller

VC1: View Controller 一

VC2: View Controller 2

所以 VC1 是导航 Controller 的 Root View Controller ,VC1 通过 show segue 连接到 VC2。

必须发生的事情:

VC1 每次打开时都必须调用一个函数,(例如 necessaryFunction())。它目前在 viewDidLoad() 中调用此函数。问题是当用户按下 VC2 中的后退按钮(导航栏上的那个)并且 VC1 现在正在显示时,viewDidLoad() 没有被调用。这意味着 necessaryFunction() 也不会被调用。

我在找什么:

我正在寻找一种方法来确保从 VC2 返回到 VC1 时调用 necessaryFunction()。我知道这可以通过委托(delegate)来解决,但是对于这么简单的事情来说这似乎过于复杂,当然还有另一种方法可以做到这一点。

也许我可以将 necessaryFunction() 放入 viewWillAppear() 中,但我认为这行不通。

顺便说一句:我正在用 Swift 编写代码。

编辑: 我找到了这篇文章:iOS how to detect programmatically when top view controller is popped? ,但它是针对 objective-C,而不是 swift。

最佳答案

These four methods can be used in a view controller's appearance callbacks to determine if it is being

作为 subview Controller 呈现解雇添加移除>。

@available(iOS 5.0, *)
open var isBeingPresented: Bool { get }

@available(iOS 5.0, *)
open var isBeingDismissed: Bool { get }


@available(iOS 5.0, *)
open var isMovingToParentViewController: Bool { get }

@available(iOS 5.0, *)
open var isMovingFromParentViewController: Bool { get }

例如, View Controller 可以

检查它是否正在消失,因为它被解散弹出通过在它的viewWillDisappear中询问自己:

通过检查表达式的方法

([self isBeingDismissed] || [self isMovingFromParentViewController]).

例如,您可以将方法调用为

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if (self.isMovingFromParentViewController())  {
        // we're already on the navigation stack
        // another controller must have been popped off
    }


}

关于ios - 检测 View Controller 何时可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603923/

相关文章:

ios - 在 IOS 上播放声音

iOS 状态恢复和 UINavigationController 模态视图

iphone - 基于 View 的 iOS 应用程序模板

ios - 如何判断 UIPageViewController 翻页是由于滑动/平移还是点击

ios - 具有合并更改的 CoreData 和 NSFetchedResultsController

ios - 如何在 UINavigationController 中插入 UITableView

ios - swift ios 无法更改导航栏标题

ios - spritekit 中的接触/碰撞问题

swift - 无法使用 segue 将值从 FirstVC 传递到 SecondVC

multithreading - 敲击按钮后应用程序崩溃