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];
}
相关推荐
疯狂的程序猴11 小时前
Flutter应用代码混淆完整指南:Android与iOS平台配置详解
后端·ios
SY.ZHOU12 小时前
移动端架构体系(五):终篇总结
flutter·ios·系统架构·安卓·鸿蒙
Digitally17 小时前
如何不用 iTunes 将 iPhone 备份到移动硬盘?
ios·iphone
sysinside17 小时前
Cisco Catalyst 9000 IOS XE 26.1.1 GA - 思科 Catalyst 9000 交换产品系列 IOS XE 系统软件
ios·cisco
rit843249917 小时前
基于STM32的触控USB鼠标设计
stm32·嵌入式硬件·计算机外设
低保和光头哪个先来17 小时前
解决 ios 使用 video 全屏未铺满页面问题
前端·javascript·vue.js·ios·前端框架
报错小能手18 小时前
SwiftUI 框架 认识 SwiftUI 视图结构 + 布局
ui·ios·swift
2501_9159214318 小时前
HTTP和HTTPS协议全面解析:技术原理与安全应用
安全·http·ios·小程序·https·uni-app·iphone
悟空爬虫-彪哥18 小时前
VRCFaceTracking安装和iPhone面捕配置教程,有bug
ios·bug·iphone
想个名字想老半天18 小时前
uni离线打包实现 ios 支付StoreKit 2,其实没有想象中那么复杂,不需要写原生插件,不需要转 uts
macos·ios·cocoa