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 小时前
flutter学习第 11 节:状态管理进阶:Provider
android·flutter·ios
2501_916013743 小时前
移动端网页调试实战,跨设备兼容与触控交互问题排查全流程
android·ios·小程序·https·uni-app·iphone·webview
叽哥4 小时前
flutter学习第 10 节:表单与输入
android·flutter·ios
猎板PCB 邹亮5 小时前
猎板PCB:专业键盘PCB板解决方案供应商
计算机外设·键盘·pcb工艺
2501_915106328 小时前
TF 上架全流程实战,从构建到 TestFlight 分发
android·ios·小程序·https·uni-app·iphone·webview
YungFan9 小时前
iOS26适配指南之UIVisualEffectView
ios·swift
Magic_ht9 小时前
UIApplicationDelegate执行说明
ios
Magic_ht9 小时前
NSThread
ios
归辞...1 天前
「iOS」————分类与扩展
ios·分类·cocoa
点灯小铭1 天前
基于STM32单片机的无线鼠标设计
stm32·单片机·计算机外设·毕业设计·课程设计