我是 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/