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];
}
相关推荐
二流小码农9 天前
鸿蒙开发:基于node脚本实现组件化运行
android·ios·harmonyos
依旧风轻9 天前
Domain 层完全指南(面向 iOS 开发者)
ios·domain·entity·sqi
续天续地9 天前
开箱即用的Kotlin Multiplatform 跨平台开发模板:覆盖网络/存储/UI/DI/CI工具链
ios·kotlin
Allen Bright9 天前
【JS-4.4-键盘常用事件】深入理解DOM键盘事件:提升用户交互体验的关键
javascript·计算机外设·交互
minos.cpp9 天前
从厨房到代码台:用做菜思维理解iOS开发 - Swift入门篇①
ios·蓝桥杯·swift
杂雾无尘9 天前
开发者必看,全面解析 iOS 架构,探索 iOS 背后的秘密!
ios·swift·apple
Digitally10 天前
如何使用 USB 数据线将文件从 PC 传输到 iPhone
ios·iphone
小天源10 天前
鼠标自动录制软件下载及使用
自动化测试·自动化·计算机外设·mouse recorder·鼠标录制·鼠标宏
小池先生10 天前
罗技键盘k380 fn按键问题 按f12不能直接打开调试,需要fn+f12
计算机外设
二流小码农10 天前
鸿蒙开发:基于DevEco Studio插件实现组件化运行
android·ios·harmonyos