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];
}
相关推荐
人月神话-Lee2 小时前
【图像处理】颜色空间——RGB之外的世界
图像处理·人工智能·ios·ai编程·swift·rgb·颜色空间
猫头虎2 小时前
猫头虎AI分享|樱桃键盘Ctrl键失效解决方案:FN+PAUSE 长按10秒恢复出厂设置保姆级教程
网络·网络协议·tcp/ip·计算机外设·键盘·机械键盘·ctrl
CocoaKier2 小时前
苹果后台年龄分级填写错误,可能导致审核被拒!
ios·apple
月诸清酒2 小时前
Codex 现在能在浏览器里跑 iOS 模拟器了
ios
橡木树的叶子3 小时前
STM32单片机+RGB三色灯模块+七色灯颜色数据发送到串口调试助手+源代码(使用cubuemx+vscode实现操作)
stm32·单片机·计算机外设
武子康3 小时前
调查研究-159 Apple WWDC 2026 定档 6/8-12:Siri 与 AI 升级,可能是苹果最关键的一次
人工智能·深度学习·ios·ai·chatgpt·apple·wwdc
2601_961194024 小时前
27考研资料|百度网盘|夸克网盘
android·xml·考研·ios·iphone·xcode·webview
2601_955767424 小时前
2026年iPhone17AR护眼膜推荐:悟赫德
人工智能·科技·ios·iphone·圆偏振光
秋雨梧桐叶落莳14 小时前
iOS——NSUserDefaults学习
学习·macos·ios·objective-c·cocoa
2601_9557674217 小时前
iPhone 17 OLED 屏幕偏振光学分析 & AR 镀膜与双护技术实践解析
人工智能·科技·ios·iphone·圆偏振光