ios - 每次 UIWindow 的 rootviewcontroller 改变时如何回调

标签 ios objective-c

我是 iOS 开发新手。我遇到了一个问题,我的用例是每次 UIWindow 的 rootviewcontroller 发生变化时都获得回调。我知道 rootviewcontroller 中有一个 rootviewcontroller.tansiondelegate 委托(delegate)属性,但在使用此委托(delegate)后我无法获得回调。

最佳答案

您可以使用KVO 来观察属性的变化。喜欢:

[[UIApplication sharedApplication].keyWindow addObserver:self forKeyPath:@"rootViewController" options:NSKeyValueObservingOptionNew context:@"rootViewControllerChange"];

当 rootViewController 改变时,将调用方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([(__bridge NSString *)context isEqualToString:@"rootViewControllerChange"] ) {
        // code what you want to do...
    }
}

注意:

当 [self class] 的实例 dealloc 时,不要忘记删除这个观察者。

[[UIApplication sharedApplication].keyWindow removeObserver:self forKeyPath:@"rootViewController" context:@"rootViewControllerChange"];

如果它不工作:

还有一个比较笨的方法:☔️

你可以使用NSNotificationCenter,当你展示一个 Controller 时,你可以

[[NSNotificationCenter defaultCenter] postNotificationName:@"PushNotificationPresentedController" object:nil userInfo:nil];

和 addObserver 在你想回调的地方接收这个通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didPresentedController) name:@"PushNotificationPresentedController" object:nil]; 

(if i have another better method, i will update my answer.)

关于ios - 每次 UIWindow 的 rootviewcontroller 改变时如何回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38911706/

相关文章:

ios - 加载更多到 UITableView 中的最后一个位置

ios - 像 LOVOO 一样的雷达 View

objective-c - 对像格式化程序这样可以多次使用的对象的并发性存疑

iphone - 如何在 Iphone 应用程序中创建日历?

ios - IESLight 可以在 SceneKit 中转换阴影吗?

ios - 如何使用 UITabbarsystemitem 设置标题

objective-c - NSString : easy way to remove UTF-8 accents from a string?

ios - 自定义推送 segue 上的 Sigabrt 错误

ios - 隐藏并删除嵌套 UIView swift 的所有空间

ios - 使用简单图形播放 iOS 网络音频时出现爆裂声和噪音