本文代码下载地址
思路:
键盘弹出的时候会发出通知
想点击空白隐藏键盘,那就给空白处添加手势
所以在发出键盘弹出的通知后,马上给keyWindow添加手势监听
只要用户在键盘弹出后,点击空白处,就会隐藏键盘
当收到键盘隐藏的通知,马上移除手势
思路有了,直接上代码:
//
// AppDelegate.m
// The keyBoard application
//
// Created by wanglei on 16/12/14.
// Copyright © 2016年 wanglei. All rights reserved.
//
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self openTouchOutsideDismissKeyboard];
return YES;
}
/** 开启点击空白处隐藏键盘功能 */
- (void)openTouchOutsideDismissKeyboard
{
[[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];
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
关键点在于要在全局有效,所以选择给window添加手势,但是不能一直给他添加手势,会覆盖掉其他的屏幕触摸事件,所以在键盘隐藏之后,马上移除掉手势。
使用方法
如果你不想自己敲,直接导入源文件(不到1kb)就好:
在AppDelegate.m 中 #import "DismissKeyboard.h"
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
加上[self openTouchOutsideDismissKeyboard];