zoukankan      html  css  js  c++  java
  • 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!!

  • 相关阅读:
    mmzrmo4delphi
    了解猫咪,和猫咪更好地相处
    无线分类
    压缩ASPX,替换ASPX多余的空格
    字符串编码转换Unicode>GB2312
    Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct bas
    ntext、text 和 image (TransactSQL)
    ICON资源
    一个简单的优酷视频链接探测与分享功能
    表单圆角大法(无JS无图片通杀所有浏览器)
  • 原文地址:https://www.cnblogs.com/csutanyu/p/3994691.html
Copyright © 2011-2022 走看看