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];
}
相关推荐
南山十一少1 天前
cherry键盘组合MacBook使用
计算机外设
开开心心就好2 天前
免费音频转文字工具,绿色版离线多模型可用
人工智能·windows·计算机视觉·计算机外设·ocr·excel·语音识别
开开心心就好3 天前
实用系统备份还原,小巧免PE备份快镜像小
windows·计算机视觉·pdf·计算机外设·迭代器模式·excel·桥接模式
kevinli3 天前
available没你想象中的可靠
ios·编译原理
CodeJourney_J4 天前
如何通过SMB协议实现手机共享电脑文件
windows·ios·smb
zxdzxdzzxd4 天前
解决Ubuntu虚拟机输入卡顿卡顿和鼠标滚轮不灵敏的问题
linux·ubuntu·计算机外设
ipad协议开发4 天前
企业微信iPad协议接口深度解析:技术原理、应用场景与开发实战
ios·企业微信·ipad
huangql5204 天前
视口进阶:移动端键盘弹出与遮挡处理实战
计算机外设