textView 和 textField 被键盘挡住的问题

  • 在控制器的自定义的view里面添加一个textView, 设置textView的代理, 在这个view里面实现这方法就可以实现键盘上移, 逻辑很简单, 一点都不复杂, 根本不用通知什么的, 太麻烦, 太污染了.
- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    CGRect frame = textView.frame;
    int offset = (frame.origin.y + frame.size.height + 62) - (self.frame.size.height-216.0);//键盘高度216  62是选择键盘上方选择文字的高度
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:0.30f];
    if (offset>0) {
        self.frame = CGRectMake(0.0f, -offset, self.frame.size.width, self.frame.size.height);
        [UIView commitAnimations];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    self.frame = CGRectMake(0, 0, self.width, self.height);
}
  • 上面最核心的其实就是计算offset的值, 后面有注释
  • 至于textField也是类似的代理方法, 看懂了这个, 那个照着一套就可以了.

我是分割线


以上是做昨天写的, 昨晚朋友推荐神器IQKeyboardManager, 三方框架, 绝逼好用, 在AppDelegate.m里面写一次就好了, 建议用pod集成, 然后在

- (void)configureKeyboardMananger {
    IQKeyboardManager *mananger = [IQKeyboardManager sharedManager];
    mananger.enable = YES;
    mananger.shouldResignOnTouchOutside = YES;
    mananger.shouldToolbarUsesTextFieldTintColor = YES;
    mananger.keyboardDistanceFromTextField = 40;
    mananger.enableAutoToolbar = NO;
}

然后, 在下面的方法中调用, 就可以一劳永逸, 以后工程中所有的textView或者textField在召唤神龙的时候, 就再也不会被键盘遮挡了.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

以上属于 <小目标 · 一天一篇> 系列文章

你可能感兴趣的:(textView 和 textField 被键盘挡住的问题)