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];
}
相关推荐
初级代码游戏3 小时前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift
for_ever_love__5 小时前
iOS:网络请求再学习
网络·学习·ios·objective-c
2501_9159214310 小时前
SwiftUI开发框架入门指南:从基础到实战
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
驱动小百科11 小时前
笔记本电脑键盘按键失灵怎么修复 教你快速恢复键盘正常输入
计算机外设·电脑·笔记本电脑键盘失灵·笔记本键盘按键没反应·笔记本键盘部分按键失灵
2501_9160074712 小时前
Python实现HTTPS爬虫的完整指南:使用requests、BeautifulSoup、Selenium和Scrapy
爬虫·python·ios·小程序·https·uni-app·iphone
LDyun_13 小时前
云手机低延迟怎么实现的?为什么云手机能够 7×24 小时在线?
ios·智能手机·安卓·玩游戏
for_ever_love__13 小时前
iOS: 网络请求第三方库的使用: AFNetworking
网络·学习·ios·objective-c·cocoa·xcode
李白你好13 小时前
强大的 Frida 重打包工具,用于 iOS 和 Android。轻松修改 Frida 特征
android·ios
蓝斯4971 天前
从.到实现一个Windows上的虚拟hid键盘设备
windows·单片机·计算机外设
zhao1zhihui1 天前
iOS Bug 定位实战:从断点、LLDB 到 Xcode 与 Instruments
ios·xcode