我使用模态segue(没有导航控制器)在viewController A和viewController B之间移动,如下所示:
viewA *first = [self.storyboard instantiateViewControllerWithIdentifier:@"viewA"];
[self presentViewController:first animated:YES completion:nil];
然后回去:
[self dismissViewControllerAnimated:YES completion:nil];
现在,我想从AppDelegate了解A或B目前是否是当前视图。 问题是我正在检查
[(AppDelegate *)[[UIApplication sharedApplication] delegate] window]
答案始终是视图A - 第一个。
我每次尝试使用模态segue时都尝试设置当前视图:
viewA *first = [self.storyboard instantiateViewControllerWithIdentifier:@"viewA"];
[self presentViewController:first animated:YES completion:^
{
[[(AppDelegate *)[[UIApplication sharedApplication] delegate] window] setRootViewController:first];
}];
但它会导致一些错误(比如无法使用" dismissViewControllerAnimated"),并且在一个有很多细分的大型项目的每个segue中都不可能像那样工作。
我应该如何使用它?我该如何以更恰当的方式检测当前视图?
答案 0 :(得分:1)
回答here
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
UIView *topView = [[topWindow subviews] lastObject];
然而,在这里做这个逻辑听起来像糟糕的架构。您需要知道当前在AppDelegate中显示哪个视图的原因是什么?
修改您似乎想要从视图控制器响应applicationWillResignActive
事件。在游戏视图控制器中使用类似的东西。
- (void) applicationWillResign {
NSLog(@"About to lose focus");
}
-(void) viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationWillResign)
name:UIApplicationWillResignActiveNotification
object:NULL];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]
removeObserver:self];
}
答案 1 :(得分:0)
appDelegate的窗口将不等于视图控制器(viewControllerA或viewControllerB)。您可以向窗口询问它的根视图控制器......
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
if (appDelegate.window.rootViewController == viewControllerA) {
// always true if you always start the app with viewControllerA
...你可以向任何视图控制器询问它所呈现的视图控制器......
if (appDelegate.window.rootViewController.presentedViewController == viewControllerB) {
// will be true if viewControllerA has presented viewControllerB
但这是一场棘手的比赛。例如,如果viewControllerB提供了一些其他viewControllerC,则上述条件将继续为真。
请参阅@Eric答案here(不是接受的答案),了解一般查找最顶层vc的方法。