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];
}
相关推荐
唐诺4 分钟前
iOS UI 框架详解
ui·ios
Zender Han20 分钟前
Flutter 轻量存储方案介绍、区别、对比和使用场景
android·flutter·ios
2501_9160074729 分钟前
XCode 15 IDE新特性:苹果集成开发环境全面升级,提升编程效率与体验
ide·vscode·macos·ios·个人开发·xcode·敏捷流程
码码哈哈0.01 小时前
2026最新可用:Mac外接2k显示器开启HiDPI,支持M芯片
macos·计算机外设
MonkeyKing71551 小时前
iOS Tagged Pointer 原理、判断方式、适用场景与避坑指南
ios·objective-c
飞Link14 小时前
iOS 27 开启“AI 开放时代”:Siri 驱动可更换背后的技术范式迁移
人工智能·ios
泉木17 小时前
KVC 详解 —— Key-Value Coding 完全指南
ios·swift
白云千载尽17 小时前
K500PRO 机械键盘使用说明书
计算机外设
sweet丶18 小时前
现有基础上增加设备生物识别登录的一个技术方案
ios