iOS關於鍵盤彈出后tableview的滑動問題


在鍵盤處理的過程中,最容易出現問題的就是,在鍵盤監聽事件中,tableView的frame的修改,網上分享的大部分都是修改frame,這樣會導致tableView的cell被遮擋,可能引起獲取不到cell的indexPath,導致無法滾動到指定位置
還有一點就是UITableViewController的使用,如果直接使用UITableViewController,鍵盤彈出事件是不用我們開發者去處理的,UITableViewController自動幫我們實現了,也就是點擊cell中的輸入框,就可以直接彈出到可見區域,進行編輯。但UITableViewController的view是一個tableView,也就是說,你想在這個controller里加一個固定位置的view,是不可能的,這就犧牲了頁面的可定制性
 

- (void)registerForKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; } - (void)keyboardWillShow:(NSNotification *)aNotification { NSDictionary* info = [aNotification userInfo]; // 注意不要用UIKeyboardFrameBeginUserInfoKey,第三方鍵盤可能會存在高度不准,相差40高度的問題 CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; // 修改滾動天和tableView的contentInset self.tableView.contentInset = UIEdgeInsetsMake(0, 0, kbSize.height, 0); self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0); // 跳轉到當前點擊的輸入框所在的cell [UIView animateWithDuration:0.5 animations:^{ [self.tableView scrollToRowAtIndexPath:_indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO]; }]; } - (void)keyboardWillBeHidden:(NSNotification *)aNotification { self.tableView.contentInset = UIEdgeInsetsZero; self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero; }
這里我們需要添加對鍵盤事件通知的檢測,而對自己的tableView所做的改變,不是frame,而是contentInset,這樣就可以保證tableView的滾動范圍為鍵盤上方的區域,可見區域為整個屏幕。
_indexPath全局變量,需要在textfield的代理中去獲取,獲取到正在編輯的輸入框所在的cell。
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textField.superview.superview];
    _indexPath = indexPath;
}
 
 

作者:翻炒吧蛋滾飯
鏈接:https://www.jianshu.com/p/c01d19b81eed
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。


免責聲明!

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



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