監聽方法:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];git
系統鍵盤會調用一次,keyboardWillShow:,而第三方鍵盤會調用三次。github
在一些頁面,textField 在頁面底部,彈出鍵盤時會遮擋輸入框,須要計算上移的高度,作一些上移。安全
我是這麼來作的app
- (void)keyboardWillShow:(NSNotification *)notification { NSDictionary *userInfo = [notification userInfo]; NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]; CGRect keyboardRect = [aValue CGRectValue]; NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSTimeInterval animationDuration; [animationDurationValue getValue:&animationDuration]; CGRect responderConvertedFrame = [_firstRespondTF.superview convertRect:_firstRespondTF.frame toView:self.view]; CGRect keyboardConvertedFrame = [self.view.window convertRect:keyboardRect toView:self.view]; CGFloat needOffsetY = responderConvertedFrame.origin.y + responderConvertedFrame.size.height - keyboardConvertedFrame.origin.y; // 若是要移動距離大於0說明有遮蓋,說明須要移動 if (needOffsetY > 0) { // scrollView如今的偏移量 + 須要移動的偏移量 = 最終要設置的偏移量 CGFloat offsetY = needOffsetY + self.scrollView.contentOffset.y; CGFloat maxOffsetY = self.scrollView.contentSize.height - self.scrollView.height; if (offsetY <= maxOffsetY) { self.contentInsetBottom = 0; [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, offsetY) animated:YES]; }else { self.contentInsetBottom = ceil(offsetY - maxOffsetY); self.scrollView.contentInset = UIEdgeInsetsMake(self.scrollView.contentInset.top, self.scrollView.contentInset.left, self.scrollView.contentInset.bottom + self.contentInsetBottom, self.scrollView.contentInset.right); [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, offsetY) animated:YES]; } } } - (void)keyboardWillHide:(NSNotification *)notification { self.scrollView.contentInset = UIEdgeInsetsMake(self.scrollView.contentInset.top, self.scrollView.contentInset.left, self.scrollView.contentInset.bottom - self.contentInsetBottom, self.scrollView.contentInset.right); self.contentInsetBottom = 0; }
系統鍵盤時,徹底沒有問題;ide
當是第三方鍵盤時,因爲走了三遍,就出現了錯誤。spa
不少文章都提到了下面這個方法:code
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier { return NO;
}
該方法的確能夠禁用掉第三方鍵盤,可是整個APP 中,都禁用掉了。而有時候,咱們只是在某些界面禁用第三方鍵盤。server
當該屬性被設置爲 YES 時,多是蘋果爲了安全考慮,第三方鍵盤是沒法彈出的。固然你可能說,這樣輸入的內容就變成黑點了,咱們能夠在鍵盤出現以後再改回來。blog
咱們在該方法中,設置一下get
- (void)textFieldDidBeginEditing:(UITextField *)textField { if (textField == _agencyTF) { textField.secureTextEntry = YES; textField.font = nil; textField.font = FONTSIZE(14); } }
而後再設置回來
- (void)keyboardWillShow:(NSNotification *)notification{ if (_agencyTF.secureTextEntry == YES) { _agencyTF.secureTextEntry = NO; _agencyTF.font = nil; _agencyTF.font = FONTSIZE(14); } }
使用IQKeyboardManager能夠很容易地解決彈起鍵盤遮蓋輸入框的問題。
地址:https://github.com/hackiftekhar/IQKeyboardManager
你還有什麼好的解決方法?歡迎留言討論