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];
}
相关推荐
tangweiguo0305198732 分钟前
Objective-C 核心语法深度解析:基本类型、集合类与代码块实战指南
开发语言·ios·objective-c
代码s贝多芬的音符33 分钟前
IOS webview打开相机 相册 选择文件上传
数码相机·ios
AI视觉网奇11 小时前
ue 捕获鼠标 键盘
计算机外设
zzcufo11 小时前
使用multimonitortool工具实现多屏显示器的映射
windows·计算机外设
我送炭你添花21 小时前
Pelco KBD300A 模拟器:01+1.KBD300A 通用键盘详解:DIP 开关与接口配置
python·计算机外设·运维开发
ACP广源盛139246256731 天前
GSV2125D@ACP#2125产品规格参数详解及产品应用分享
嵌入式硬件·计算机外设·音视频
鹏多多1 天前
Flutter下拉刷新上拉加载侧拉刷新插件:easy_refresh全面使用指南
android·前端·ios
最后一个bug1 天前
浅显易懂的讲解MMU是如何使用4级页表把虚拟地址转化为物理地址的~
linux·服务器·开发语言·系统架构·计算机外设
驱动探索者1 天前
[缩略语大全]之[IOS]篇
ios
kkk_皮蛋2 天前
在移动端使用 WebRTC (Android/iOS)
android·ios·webrtc