UIScrollView點擊空白處退出鍵盤方法(含與鍵盤手寫沖突導致崩潰解決)

UIScrollView 上如果有UITextField的話,結束編輯(退出鍵盤)直接用touchesBegan方法無效,需要再給UIScrollView加一個分類,重寫幾個方法。
網上已經有很多前輩給了相關代碼是這樣的(閱前提示:這樣是有問題的!):

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}

這樣會有一個嚴重問題,就是使用手寫輸入法輸入中文會導致崩潰(雖然使用手寫輸入法的人不多,但也不能無視他們)。被坑死,問題是百度出來尼瑪80~90%全是這種解決方法。坑死人!

有一些前輩對于“UIScrollView點擊空白處退出鍵盤”就提出了另一種解決方法:加一層view,給view一個點擊事件,退出鍵盤。

但是我的項目中已經被前一種方法坑了,已經有用戶反映手寫崩潰,換第二種方法的話很麻煩,需要修改之后重新提交審核,不能及時解決,我需要及時的用JSPatch線上打補丁解決。調試了很久,我發現手寫鍵盤在調用UIScrollView的這個分類的方法時,self的類型是UIKBCandidateCollectionView,一種系統沒有暴露出來的類型,應該是UIScrollView的一個子類,所以解決辦法就呼之欲出了,直接上代碼。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesBegan:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesBegan:touches withEvent:event];
        }
    }
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesMoved:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesMoved:touches withEvent:event];
        }
    }
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesEnded:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesEnded:touches withEvent:event];
        }
    }
}

手寫輸入法崩潰完美解決O(∩_∩)O~~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,067評論 25 708
  • 2017.02.22 可以練習,每當這個時候,腦袋就犯困,我這腦袋真是神奇呀,一說讓你做事情,你就犯困,你可不要太...
    Carden閱讀 1,373評論 0 1
  • iOS 手寫輸入法奔潰,一種方法是常見的新建一個view監聽點擊手勢,隱藏鍵盤,然后這個view最后加入到self...
    sll_閱讀 1,524評論 0 0
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,198評論 4 61
  • 翻譯自“View Controller Programming Guide for iOS”。 1 彈出視圖控制器...
    lakerszhy閱讀 3,608評論 2 20