美文网首页
键盘监控代码

键盘监控代码

作者: 摸摸头发 | 来源:发表于2021-10-09 09:21 被阅读0次
    - (void)viewDidLoad {
        self.automaticallyAdjustsScrollViewInsets = NO;
        //监听键盘的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotify:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    -(void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        _wasKeyboardManagerEnabled = [[IQKeyboardManager sharedManager]isEnabled];
        [[IQKeyboardManager sharedManager] setEnable:NO];
    }
    -(void)viewDidDisappear:(BOOL)animated {
    {
        [super viewWillDisappear:animated];
        [[IQKeyboardManager sharedManager] setEnable:_wasKeyboardManagerEnabled];
    }
    /**
     *  点击了return按钮(键盘最右下角的按钮)就会调用
     */
    - (BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [self sendMessage];
        return YES;
    }
    /**
     *  当键盘改变了frame(位置和尺寸)的时候调用
     */
    -(void)keyboardWillChangeFrameNotify:(NSNotification*)notify {
        // 0.取出键盘动画的时间
        CGFloat duration = [notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        // 1.取得键盘最后的frame
        CGRect keyboardFrame = [notify.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        // 2.计算控制器的view需要平移的距离
        CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
        // 3.执行动画
        [UIView animateWithDuration:duration animations:^{
            self.myTableView.frame = CGRectMake(0, 0, SCREENW, SCREENH + transformY - self.inputView.height);
            self.tableViewBottomConstraint.constant = -transformY + 44;// tableView的bottom距父视图bottom的距离
            self.inputView.transform = CGAffineTransformMakeTranslation(0, transformY);
            [self scrollTableViewToBottom];
        }];
    }
    /**
     *  tableView快速滚动到底部
     */
    - (void)scrollTableViewToBottom {
        if (self.messageFrames.count) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(self.messageFrames.count - 1) inSection:0];
           [self.myTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

    相关文章

      网友评论

          本文标题:键盘监控代码

          本文链接:https://www.haomeiwen.com/subject/jotqoltx.html