Trigger an event / method when UIWindow RootViewController changes SWIFT

删除回忆录丶 提交于 2019-12-11 01:56:43

问题


I'm working on an iOS framework. I have a requirement to log events when user enters or exits a particular View Controller. For that I was thinking if somehow I could be able to register a notification to trigger a custom method when the root view controller changes. Or perhaps use KVO. But I don't understand how to do this from an implementation point of view since I cannot find any such notification.

Any help in this regard would be highly appreciated. Thanks.

Please note that this is a framework project. So the framework is built and then added/embedded into another app. I don't have any information about the view controllers in that app. The only thing I can access is UIWindow's root view controller. So, I need to know when a change occurs in it.


回答1:


Got it working. The answer was method swizzling. Not recommended as a first solution to the problem. But if used carefully and you know exactly what you are doing that it is the way to go.

Found a very useful article here: Method Swizzling




回答2:


You can override UIViewController's viewWillAppear and viewWillDisappear to know when a view controller is about to be presented/dismissed.

Alternatively you can use viewDidAppear and viewDidDisappear.

If you want to do the logging on users behalf then you really have two options:

1. provide a base UIViewController sub-class for them to override, which implements a required logic in viewWillAppear/viewWillDisappear methods.

2. implement convenience methods (like logAppearEvent, logDisappearEvent) for them to call manually on their own in their UIViewController subclasses.



来源:https://stackoverflow.com/questions/36124902/trigger-an-event-method-when-uiwindow-rootviewcontroller-changes-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!