在 lxt 的指导下,我设法把一些东西放在一起。这并不理想,但它似乎对我有用。
我在 airplay 按钮上添加了一个轻击手势,以了解何时开始观察关键窗口。当它被点击时,我开始观察。
- (void)airplayTapped:(UITapGestureRecognizer *)gesture {
NSLog(@"airplay added");
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (!keyWindow) {
keyWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
}
// this occurs before the airplay popover view is added, so this is the
// number we want to check for in observeValueForKeyPath: to determine
// if the view has been dismissed
self.windowSubviews = keyWindow.layer.sublayers.count;
[keyWindow addObserver:self forKeyPath:@"layer.sublayers" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (![keyPath isEqualToString:@"layer.sublayers"]) {
return;
}
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (!keyWindow) {
keyWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
}
if (keyWindow.layer.sublayers.count == self.windowSubviews) {
NSLog(@"airplay removed");
[keyWindow removeObserver:self forKeyPath:@"layer.sublayers"];
}
}
请注意,UIKit 中的任何内容都不能保证与 KVO 兼容,因此我们可以观察其层的子层,而不是观察窗口的子视图。
正如 lxt 所说,这很容易破坏,但就我的目的而言,它会完成这项工作。