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];
}
相关推荐
mzhan0171 分钟前
电脑:鼠标
计算机外设·电脑
Digitally1 小时前
iPhone 卡在恢复模式:如何修复(分步指南)
ios·iphone
WHD3061 小时前
苏州服务器维修哪家好/公司推荐
linux·ubuntu·centos·计算机外设·电脑·unix·安全架构
vx-bot5556661 小时前
企业微信ipad协议的协议状态机与生命周期管理
ios·企业微信·ipad
ONE_SIX_MIX1 小时前
debian13 无显示器的 服务器,开机不自动加载nvidia 驱动的,解决
运维·计算机外设
ITKEY_2 小时前
macOS通过命令行启动iOS模拟器
macos·ios
00后程序员张2 小时前
iPhone 无需越狱文件管理 使用Keymob查看导出文件
android·ios·小程序·https·uni-app·iphone·webview
OneCrab2 小时前
Iphone漏洞利用工具包 Coruna DarkSword
ios·cocoa·iphone
2501_915106322 小时前
不依赖 Mac 也能做 iOS 开发?跨设备开发流程
ide·vscode·macos·ios·个人开发·swift·敏捷流程
2501_916008892 小时前
Unity3D iOS 应用防篡改实战 资源校验、 IPA 二进制保护
android·ios·小程序·https·uni-app·iphone·webview