iOS - 如何检查是否存在模态视图

时间:2011-03-17 10:56:16

标签: ios views modal-dialog

有没有办法检查是否存在模态视图?我想仅在存在模态视图时才运行方法。此外,如果我有多个模态视图,有没有办法检查是否存在某个模态视图。

我使用以下代码来呈现和消除模态视图:

    [self presentModalViewController:myModalView animated:YES];
    [self dismissModalViewControllerAnimated:YES];

提前谢谢!

干杯, 埃文

PS。我的模态视图有一个视图控制器,但我想检查模态视图是否存在于异步运行的单独类中。

4 个答案:

答案 0 :(得分:75)

您是否正在检查父视图控制器中是否存在模态视图控制器?如果是这样,您只需检查视图控制器的modalViewController属性:

BOOL modalPresent = (self.modalViewController);

如果要检查特定的模态视图控制器,可以像这样获取模态视图控制器的类名:

NSString *modalClassName = NSStringFromClass([self.modalViewController class]);

答案 1 :(得分:57)

您可以使用:self.presentedViewController进行查询,返回The view controller that is presented by this view controller, or one of its ancestors in the view controller hierarchy.

答案 2 :(得分:6)

对我有用的是:

// this is the trick: set parent view controller as application's window root view controller
UIApplication.sharedApplication.delegate.window.rootViewController = viewController;

// assert no modal view is presented
XCTAssertNil(viewController.presentedViewController);

// simulate button tap which shows modal view controller
[viewController.deleteButton sendActionsForControlEvents:UIControlEventTouchUpInside];

// assert that modal view controller is presented
XCTAssertEqualObjects(viewController.presentedViewController.class, MyModalViewController.class);

据我测试,这适用于iOS7和iOS8。但是,没有尝试使用iOS6。

答案 3 :(得分:1)

您可以检查来自父view controller

的模态view controller的存在
if ( [[self presentingViewController] presentingViewController] ) {

}