如何确定当前视图控制器是否处于活动状态,如果处于活动状态则执行代码 [英] How to determine whether current view controller is active, and execute code if active

查看:35
本文介绍了如何确定当前视图控制器是否处于活动状态,如果处于活动状态则执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,有一个 ViewController.swift 文件和一个 popupViewController.swift 文件.在应用程序中,当我打开 popupViewController 并使用 storyboard segue 作为 presentModally 然后从 popupViewController 返回到 ViewController 时使用代码 dismiss(),方法 viewDidLoad、viewWillAppear、viewDidAppear、ViewWillLayoutSubviews等没有任何效果,它们只执行一次,当我回去时不会重复.所以,我想在每次 viewController.swift 处于活动状态时执行代码.我在 stackoverflow 中找不到关于此的有用信息.

In my app, there is a ViewController.swift file and a popupViewController.swift file. Inside the app, when I open the popupViewController with storyboard segue as presentModally and then come back from popupViewController to ViewController with the code dismiss(), the methods viewDidLoad, viewWillAppear, viewDidAppear, ViewWillLayoutSubviews etc. nothing works, they execute just once and don't repeat when I go and return back. So, I want to execute the code every time when viewController.swift is active. I couldn't find a useful info in stackoverflow about this.

与此同时,我对通知和观察者知之甚少(如果确实需要的话),因此,您能否详细说明如何在 Swift 中做到这一点(不是objective-c)?我的意思是如何确定当前视图控制器是否处于活动状态.

Meanwhile, I don't know much about notification and observers(if certainly needed), therefore, can you tell step by step in detail how to do that in Swift (not objective-c)? I mean how to determine if current view controller is active.

我正在从 StoryBoard segue、presentModally 导航.故事板中没有导航控制器.

I am navigating from StoryBoard segue, presentModally. There is no Navigation Controller in storyboard.

我尝试了一些代码,但没有任何反应.我到目前为止的观点是:

I tried some codes but nothing happens. The point I came so far is:

override func viewDidLoad() {
        super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector:#selector(appWillEnterForeground), name:UIApplication.willEnterForegroundNotification, object: nil) 
}

@objc func appWillEnterForeground() {
        print("asdad") //nothing happens
        if self.viewIfLoaded?.window != nil {
            // viewController is visible
            print("CURRENT VİEW CONTROLLER") //nothing happens
        }
    }

推荐答案

正如我在评论中提到的,我不使用故事板.可能有一种方法可以创建放松转场 - 或者可能没有 - 但是 [here's a link][1] 可以帮助您使用仅情节提要的方式来解决您的问题.快速搜索模态"找到了 9 个,第二个开始详细介绍.

As mention in my comments, I don't use storyboards. There may be a way to create an unwind segue - or maybe not - but [here's a link][1] that may help you with a storyboard-only way of fixing your issue. A quick search on "modal" turned up 9 hits, and the second one starts going into details.

我认为问题在于模态是什么.基本上,正确执行 viewDidAppear 的第一个视图控制器仍然可见.因此,当您的第二个 VC 出现时,它实际上不会执行 viewDidDisappear.

I'm thinking the issue is with what modality is. Basically, your first view controller, which properly executed viewDidAppear, is still visible. So it's effectively not executing viewDidDisappear when your second VC is presented.

您可能想稍微改变一下您的概念 - 应用程序窗口(认为 AppDelegate 和/或 SceneDelegate 成为 active,其中 UIViewController 有一个是 initializeddeinitialized,还有一个根 UIViewloaded, 出现*然后消失*.这很重要,因为您要做的是从模态 VC 的 viewDidDisappear 覆盖发送通知.

You might want to change your concept a bit - an application window (think AppDelegate and/or SceneDelegate become active, where a UIViewController has a is initialized and deinitialized, along with a root UIView that is loaded, appears* and disappears*. This is important, because what you want to do is send your notification from the modal VC's viewDidDisappear override.

首先,我发现将所有通知定义放在一个扩展中最容易:

First, I find it easiest to put all your notication definitions in an extension:

extension Notification.Name {
    static let modalHasDisappeared = Notification.Name("ModalHasDisappeared")
}

这不仅有助于减少字符串拼写错误,而且还允许 Xcode 的代码完成.

This helps not only reduce string typos but also is allows Xcode's code completion to kick in.

接下来,在您的第一个视图控制器中,向此通知添加观察者:

Next, in your first view controller, ad an observer to this notification:

init() {
    super.init(nibName: nil, bundle: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(modalHasDisappeared), name: .modalHasDisappeared, object: nil)
}
required init?(coder: NSCoder) {
    super.init(coder: coder)
    NotificationCenter.default.addObserver(self, selector: #selector(modalHasDisappeared), name: .modalHasDisappeared, object: nil)
}
@objc func modalHasDisappeared() {
    print("modal has disappeared")
}

为了清楚起见,我添加了两种形式的init.由于您使用的是故事板,我希望 init(coder:) 是您需要的.

I've added both forms of init for clarity. Since you are using a storyboard, I'd expect that init(coder:) is the one you need.

最后,当模态消失时发送通知:

Finally, just send the notification when the modal has disappeared:

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.post(name: .modalHasDisappeared, object: nil, userInfo: nil)
}

这不会发送任何数据,只是模态消失的事实.如果要发送数据 - 例如,字符串或表格单元格值,请将 object 参数更改为:

This sends no data, just the fact that the modal has disappeared. If you want to send data - say, a string or a table cell value, change the object parameter to it:

NotificationCenter.default.post(name: .modalHasDisappeared, object: myLabel, userInfo: nil)

并在您的第一个 VC 中进行以下更改:

And make the following changes in your first VC:

NotificationCenter.default.addObserver(self, selector: #selector(modalHasDisappeared(_:)), name: .modalHasDisappeared, object: nil)

@objc func modalHasDisappeared(_ notification:Notification) {
    let label = notification.object as! UILabel!
    print(label.text)
}

最后的笔记:

  • 重复一遍,请注意,通过声明对 Notification.Name 的扩展,我只有一个地方声明了一个字符串.
  • AppDelegateSceneDelegate 中没有代码,也没有任何对`UIApplication() 的引用.尝试将视图(和视图控制器)视为出现/消失,而不是背景/前景.
  • 虽然第一个视图在背景中视觉,但它仍然可见.所以诀窍是针对消失的模态视图进行编码.
  • To repeat, note that by declaring an extension to Notification.Name, I've only have one place where I'm declaring a string.
  • There is no code in AppDelegate or SceneDelegate, nor any references to `UIApplication(). Try to think of the view (and view controller) as appearing/disappearing, not background/foreground.
  • While the first view is visually in the background, it's still visible. So the trick is to code against the modal view disappearing instead.

这篇关于如何确定当前视图控制器是否处于活动状态,如果处于活动状态则执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆