美文网首页
ios UITextView或者UITextField随键盘弹出

ios UITextView或者UITextField随键盘弹出

作者: FM_0138 | 来源:发表于2018-06-26 10:45 被阅读0次

在写聊天时,希望输入框随键盘一起弹起,具体做法如下:

还有如果是第三方键盘导致的键盘回调三次的坑,也可以通过如下方法解决

1,先注册监听方法:

在这里注意:一定要是监听的"UIKeyboardWillShowNotification"和"UIKeyboardWillHideNotification",不然会出现意想不到的结果, 我就是因为把"UIKeyboardWillShowNotification"写成了"UIKeyboardDidShowNotification", 结果输入框会有多次跳动的感觉(第三方键盘导致的键盘回调三次的坑)

- (void)registerForKeyboardNotifications {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)                                        name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)                                        name:UIKeyboardWillHideNotification object:nil];

}

2, 键盘将要出现时的响应方法如下:

这样输入框就会随键盘一起弹出了

- (void)keyboardWasShown:(NSNotification*)aNotification {

    NSDictionary* info = [aNotification userInfo];

    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    self.keyboardHeight = kbSize.height;

// 获取键盘动画时间

    CGFloat animationTime  = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];

// 定义好动作

    void (^animation)(void) = ^void(void) {

        self.editView.frame = CGRectMake(0, self.tableView.qp_bottom, SCREEN_WIDTH, 500);

};

if (animationTime > 0) {

        [UIView animateWithDuration:animationTime animations:animation];

    } else {

        animation();

    }

3, 键盘将要消失时的响应方法如下:

- (void)keyboardWillBeHidden:(NSNotification*)aNotification {

NSLog("键盘将要消失");

}

4, 在dealloc方法中一定要移除观察者

- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

相关文章

网友评论

      本文标题:ios UITextView或者UITextField随键盘弹出

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