# 点阴影区关闭 Modal View Controller

参考：[Close Modal View Controller by tap the shadow region](http://mengxiangping.com/?p=121)

如何实现用户点击阴影区域，将当前出现的 **ModalViewController**消失

![modalViewC](https://www.doruby.com/wp-content/uploads/2016/06/modalViewC.png)

首先了解一下: **UIApplicationMain**

```

int main(int argc, char *argv[]) 
{ 
    @autoreleasepool { 
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 
    } 
}
```

argc 与 argv 是标准的 c main 函数参数。 第三个参数是接收事件响应的主要对象(principalClassName)，如果存在的话必须是继承 UIApplication , 第四个 delegateClassName, 实现 UIApplicationDelegate 中的协议方法.

任何时刻你点击屏幕，principalClassName 都会监听, 并执行 sendEvent 方法, 所以我们只要拦截这个方法，然后做我们想做的事情就可以了。

实现

测试环境：iOS5, iPad

改变 main 的第三个参数对象为 我们自己定义的一个 MyAppplication 类。

main.m

```

int main(int argc, char *argv[]) 
{ 
    @autoreleasepool { 
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 
    } 
}
```

.h file

```

#import 

@interface MyApplication : UIApplication

@end
```

.m file

```

#import "MyApplication.h"

@implementation MyApplication

-(void)sendEvent:(UIEvent *)event{

  [super sendEvent:event];

  // 关键是在这里拿到点击事件后,如果判断点击的是阴影区, 阴影区的View 是一个私有类, 名字叫UIDimmingView, 所以如果响应的点击事件是在这个View上的，我们就可以关闭当前的ModalView
  UITouch* touch = [[[event allTouches] allObjects] lastObject];

  if ([NSStringFromClass([[touch view] class]) isEqualToString:@"UIDimmingView"]) {
      UIViewController * vc = [[[self keyWindow] rootViewController] presentedViewController]; // 找到正在显示的控制器
      [vc dismissModalViewControllerAnimated:YES];
  }
}

@end
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.doruby.com/mobile/tips-1/dian-yin-ying-qu-guan-bi-modal-view-controller.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
