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~~