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];
}
相关推荐
Digitally7 小时前
6 种简易方法轻松连接 iPad 与电脑
ios·电脑·ipad
ZC跨境爬虫10 小时前
Playwright模拟鼠标滚轮实战:从原理到百度图片_豆瓣电影爬取
爬虫·python·计算机外设
2501_9159214310 小时前
uni-app一键生成iOS安装包并上传TestFlight全流程
android·ios·小程序·https·uni-app·iphone·webview
sp42a10 小时前
如何在 NativeScript 中使用 iOS 的 Metal 着色器
ios·着色器·nativescript
Mr_CrazyPeter1 天前
iONSPlayer 1.1.1版本发布
游戏·ios·模拟器
秋雨梧桐叶落莳1 天前
iOS——UI入门
ui·ios·cocoa
zhensherlock1 天前
Protocol Launcher 系列:Agenda 优雅组织你的想法与日程
javascript·macos·ios·typescript·node.js·mac·ipad
Rhys..1 天前
webdriveragent setup教程
ios
报错小能手1 天前
ios开发方向——swift内存基础
开发语言·ios·swift
SY.ZHOU1 天前
移动端架构体系(二):本地持久化与动态部署
flutter·ios·安卓