Recently, due to project needs, sometimes we need to dismiss off the keyboard at any time.
Naturally we'll think of keyboard notifications uikeyboarddidshownotification and Uikeyboarddidhidenotification,
These two notifications let you know if the current keyboard is visible, and then go dismisss if visible. In this case, we need to find out the culprit of show the keyboard.
The stupidest way to do this is to add code to all the places where you want to display the keyboard, and then record the equivalent components in one place. But you and I are not stupid, right:]
If you are familiar with respond chain, you will know that the display keyboard must be the current first responder.
They just need to know the current first responder to call Resignfirstresponder again. As follows:
UIWindow *keywindow = [[UIApplication sharedapplication] Keywindow]; UIView *firstresponder = [Keywindow performselector: @selector (FirstResponder)];[ FirstResponder Resignfirstresponder];
Yes, you may have noticed that the perform @selector (firstresponder) on window is a private API.
There are a few other ways to link here.
@implementation UIView (Findfirstresponder)-(ID) findfirstresponder{ if (self.isfirstresponder) { return Self; } For (UIView *subview in self.subviews) { id responder = [subView Findfirstresponder]; if (responder) return responder; } return nil;} @end
IOS 7+
-(ID) findfirstresponder{ if (self.isfirstresponder) { return self; } For (UIView *subview in self.view.subviews) { if ([SubView Isfirstresponder]) { return subView; } } return nil;}
The overall feeling is not too elegant, and if your interface with a lot of child viewvonroller also do not know will be feasible, if replaced by ios8,ios9 ... Whether it is OK.
In the almighty Google and StackOverflow finally found the most elegant method:
[[UIApplication sharedapplication] sendaction: @selector (resignfirstresponder) To:nil From:nil Forevent:nil];
In the Apple document, the target is explained to:
The object to receive the action message. If target nil is, the app sends the message to the first responder, from whence it progresses up the responder chain Unti L it is handled.
=======================
YES, this is the what we want!!
IOS in any interface Dismiss Keyboard