在項(xiàng)目開發(fā)中,經(jīng)常遇到鍵盤遮擋問題拴鸵,那我們應(yīng)該怎么去處理呢吩跋?
上面是我項(xiàng)目中的一個(gè)頁(yè)面,其中tableView上有多個(gè)textFiled,多次點(diǎn)擊新建商品規(guī)格窖认,tableView會(huì)出現(xiàn)多個(gè)價(jià)格豫柬,庫(kù)存,每日庫(kù)存多個(gè)section扑浸。那么對(duì)于這樣的頁(yè)面我們應(yīng)該怎么處理呢烧给?
下面就具體介紹如何處理這樣的問題。
1.設(shè)置tableView的鍵盤退出模式:
self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
2.監(jiān)聽鍵盤彈出事件
//監(jiān)聽鍵盤彈出事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShowWithNotification:) name:UIKeyboardWillShowNotification object:nil];
其中keyBoardWillShowWithNotification將在后面具體介紹喝噪。
3.第三步是關(guān)鍵一步础嫡,將tableView的每個(gè)textFiled的代理設(shè)成self.在代理方法中做如下處理:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
self.activedTextFieldRect = [textField convertRect:textField.frame toView:self.tableView];
}
其中activedTextFiledRect為當(dāng)前正在編輯的textField的frame相對(duì)于tableView的位置。
4.在keyBoardWillShowWithNotification處理鍵盤彈出事件
- (void)keyBoardWillShowWithNotification:(NSNotification *)notification {
//取出鍵盤最終的frame
CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//取出鍵盤彈出需要花費(fèi)的時(shí)間
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//獲取最佳位置距離屏幕上方的距離
if ((self.activedTextFieldRect.origin.y + self.activedTextFieldRect.size.height) > ([UIScreen mainScreen].bounds.size.height - rect.size.height)) {//鍵盤的高度 高于textView的高度 需要滾動(dòng)
[UIView animateWithDuration:duration animations:^{
self.tableView.contentOffset = CGPointMake(0, 64 + self.activedTextFieldRect.origin.y + self.activedTextFieldRect.size.height - ([UIScreen mainScreen].bounds.size.height - rect.size.height));
}];
}
通過self.activedTextFieldRect.origin.y + self.activedTextFieldRect.size.height) 與 ([UIScreen mainScreen].bounds.size.height - rect.size.height)的比值就可以判斷當(dāng)前處于編輯狀態(tài)的textField是否被鍵盤遮擋酝惧。其中64是自己根據(jù)UI榴鼎,調(diào)整的一個(gè)適當(dāng)值,可根據(jù)視覺做適當(dāng)調(diào)整晚唇。
最后記得在dealloc方法中移除觀察者巫财。