键盘隐藏的算法

键盘覆盖输入框是一个很恶心的事,接下来是我通过算法来实现键盘的合理处置方式:

NSDictionary *userInfo = [notif userInfo];
NSValue *animationDurationObject = userInfo[UIKeyboardAnimationDurationUserInfoKey];
NSValue *keyboardEndRectObject = userInfo[UIKeyboardFrameEndUserInfoKey];
double animationDuration = 0.f;
CGRect keyboardEndRect = CGRectZero;
[animationDurationObject getValue:&animationDuration];
[keyboardEndRectObject getValue:&keyboardEndRect];
CGPoint point1 = [selectTf convertPoint:self.scView.bounds.origin toView:self.view.window];
CGFloat height = selectTf.frame.size.height;
CGPoint changePoint = CGPointMake(0, point1.y+height>keyboardEndRect.origin.y?point1.y+height-keyboardEndRect.origin.y+self.scView.contentOffset.y:self.scView.contentOffset.y);
[self.scView setContentOffset:changePoint animated:YES];

其中的selectTf指的是你光标所在的那个控件,self.scView指的是UIScrollview或者是UITableView,这样就可以通过CGPoint changePoint = CGPointMake(0, point1.y+height>keyboardEndRect.origin.y?point1.y+height-keyboardEndRect.origin.y+self.scView.contentOffset.y:self.scView.contentOffset.y);拿到偏移量赋值给self.scView

=================================================
下边是另外一个方法来处理这个键盘的问题,这个也很实用就是一个第三方键盘IQKeyboardManager,也可以在code4app上看到类似demoIQKeyboardManagerDemo,这个第三方只需要导入到工程中,不需要做任何设置就可以使用了。效果如图所示:

键盘隐藏的算法_第1张图片
1.png

当然如何你在某一个页面不想使用这种键盘可以使用以下代码屏蔽:

  1. 关闭第三方键盘
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [[IQKeyboardManager sharedManager] setShouldToolbarUsesTextFieldTintColor:NO];
  2. 开始第三方键盘
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setShouldToolbarUsesTextFieldTintColor:YES];

你可能感兴趣的:(键盘隐藏的算法)