自学内容网 自学内容网

iOS 键盘弹出页面上移

就是通过系统的一个通知,获取到键盘即将展示,和即将消失的时机,并通过
通知获取到键盘的高度和键盘弹出的duration, 我们上移页面frame的时候也用这个
duration,就能产生和键盘同步移动的效果,下面是代码

添加和移除通知监听

- (void)addKeyboardObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillDisappear:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeKeyboardObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

在监听方法中修改视图的frame

- (void)keyboardWillShow:(NSNotification *)noti
{
    CGRect keyboardRect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat boardHeight = keyboardRect.size.height;
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    LIVWeakify(self);
    [UIView animateWithDuration:duration animations:^{
        LIVStrongify(self);
        self.viewContent.y -= boardHeight;
    }];
    [self.viewContent addGestureRecognizer:self.endEditingTap];
}

- (void)keyboardWillDisappear:(NSNotification *)noti
{
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    LIVWeakify(self);
    [UIView animateWithDuration:duration animations:^{
        LIVStrongify(self);
        self.viewContent.y = self.view.height * 0.25;
    }];
    [self.viewContent removeGestureRecognizer:self.endEditingTap];
}

原文地址:https://blog.csdn.net/LIUXIAOXIAOBO/article/details/142969166

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!