UIScrollView 上如果有UITextField的話,結(jié)束編輯(退出鍵盤)直接用touchesBegan方法無效,需要再給UIScrollView加一個分類,重寫幾個方法。
網(wǎng)上已經(jīng)有很多前輩給了相關(guān)代碼是這樣的(閱前提示:這樣是有問題的!):
- (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];
}
這樣會有一個嚴重問題,就是使用手寫輸入法輸入中文會導(dǎo)致崩潰(雖然使用手寫輸入法的人不多,但也不能無視他們)。被坑死,問題是百度出來尼瑪80~90%全是這種解決方法??铀廊?!
有一些前輩對于“UIScrollView點擊空白處退出鍵盤”就提出了另一種解決方法:加一層view,給view一個點擊事件,退出鍵盤。
但是我的項目中已經(jīng)被前一種方法坑了,已經(jīng)有用戶反映手寫崩潰,換第二種方法的話很麻煩,需要修改之后重新提交審核,不能及時解決,我需要及時的用JSPatch線上打補丁解決。調(diào)試了很久,我發(fā)現(xiàn)手寫鍵盤在調(diào)用UIScrollView的這個分類的方法時,self的類型是UIKBCandidateCollectionView,一種系統(tǒng)沒有暴露出來的類型,應(yīng)該是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~~