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];
}
相关推荐
Johnny Tong11 小时前
iOS 获取设备占用内存
ios·内存·host_vm
木兰不吃草11 小时前
如何在 Mac 上下载安装仙剑游戏仙剑世界?可以通过IPA砸壳包安装非常简单
游戏·macos·ios·游戏程序·mac
帅次11 小时前
Flutter 异步编程利器:Future 与 Stream 深度解析
android·flutter·ios·小程序·kotlin·webview·android-studio
小鹿撞出了脑震荡15 小时前
Effective Objective-C 2.0 读书笔记——大中枢派发
开发语言·ios·objective-c
struggle202516 小时前
Ollmao (OH-luh-毛程序包及源码) 是一款原生 SwiftUI 应用程序,它与 Ollama 集成,可在 Mac 上本地运行强大的 AI 模型
ios·swiftui·swift
神仙别闹1 天前
基于IOS实现各种倒计时功能
macos·ios·cocoa
gp1032 天前
iOS事件传递和响应
ios·响应链·事件传递
SunshineBrother2 天前
Flutter go_router 路由管理详解&封装
android·flutter·ios
陈老老老板2 天前
让编程变成一种享受-明基RD320U显示器
计算机外设
是阿建吖!3 天前
【C++】IO流
开发语言·c++·cocoa