iOS 在任意界面 Dismiss Keyboard


最近由於項目需要,有些時候我們需要在任意時刻dismiss掉鍵盤。

很自然的我們會想到鍵盤通知 UIKeyboardDidShowNotification和UIKeyboardDidHideNotification,

通過這兩個通知可以知道當前鍵盤是否可見,如果可見再去dismisss掉。這樣的話還需把show the keyboard的元凶找出來。

最笨的方法就是在所有要顯示鍵盤的地方添加代碼,然后把相當的組件記錄在某一個地方。But你和我都不會笨是吧 :]

 

如果熟悉respond chain的話,就知道,顯示鍵盤的一定是當前的first responder。

那們就只需要知道當前的first responder就再調用resignFirstResponder就可以了。如下:

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView   *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
[firstResponder resignFirstResponder];

 是的,你可能已經注意到,window上perform的@selector(firstResponder)是一個私有API。

在鏈接這里還有其它一些方法。

@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;
}

總感覺不太優雅,而且如果你的界面用了很多的Child ViewVonroller也不知道會不會可行,如果換成iOS8,iOS9...是否還行。

在萬能的google和stackoverflow中終於還是找到了最優雅的方法:

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

 在蘋果的文檔中對target解釋到:

The object to receive the action message. If target is nil, the app sends the message to the first responder, from whence it progresses up the responder chain until it is handled.

=======================

YES, this is what we want!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM