一句代码搞定,所有页面点击空白处隐藏键盘

首先新建一个appdelegate的分类

代码如下:

#import "AppDelegate.h"
@interface AppDelegate (DismissKeyboard)
/** 开启点击空白处隐藏键盘功能 */
- (void)openTouchOutsideDismissKeyboard;
@end
@implementation AppDelegate (DismissKeyboard)
/** 开启点击空白处隐藏键盘功能 */
- (void)openTouchOutsideDismissKeyboard
{
    /** 给window注册监听*/
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addGesture) name:UIKeyboardDidShowNotification object:nil];
}
- (void)addGesture
{
    /** 添加手势*/
    [self.window addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disappearKeyboard)]];
}
- (void)disappearKeyboard
{
    /**隐藏键盘*/
    [self.window endEditing:YES];
    [self.window removeGestureRecognizer:self.window.gestureRecognizers.lastObject];
}
- (void)dealloc
{
    /**取消键盘*/
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end

然后接下来只需要在:

 * 1.在AppDelegate.m#import "DismissKeyboard.h"
  * 2.在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  *  加上[self openTouchOutsideDismissKeyboard];

就大公告成了,希望可以帮助到你,有疑问可以关注我,我们一起探讨哦。
http://download.csdn.net/detail/tubiebutu/8894417
需要的可以下载下来

你可能感兴趣的:(通知)