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];
}
相关推荐
FreeBuf_16 小时前
苹果紧急发布iOS 15.8.7更新以防御“Coruna“漏洞利用工具包
macos·ios·cocoa
开心就好202518 小时前
移动应用上架到应用商店的完整指南:原理与详细步骤
后端·ios
TESmart碲视19 小时前
Mac+PC双系统如何共享双屏?KVM切换器选购的5个关键指标|TESmart用户真实体验复盘
macos·计算机外设·kvm切换器·tesmart·双屏kvm切换器·碲视
wx_xsooop_wx20 小时前
iOS 被拒 4.3a Cocos【全面解读】
ios
00后程序员张20 小时前
使用克魔助手(Keymob)查看 iOS 设备日志与崩溃报告
android·macos·ios·小程序·uni-app·cocoa·iphone
iOS日常20 小时前
Xcode SPM 太慢/报错?代理 + 缓存修复
ios
2501_9159184120 小时前
通过IPA 结构调整和资源指纹变化来处理 iOS 应用相似度问题
android·ios·小程序·https·uni-app·iphone·webview
春日见1 天前
车载系统中的CPU与内存监管
java·开发语言·驱动开发·docker·计算机外设
泉木1 天前
isa 指针、元类、继承链
ios·objective-c