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];
}
相关推荐
杭城小刘2 小时前
Weex 底层原理与 APM
ios·前端框架·weex
应用市场3 小时前
键盘无冲(NKRO)的嵌入式实现原理——从鬼键问题到全键无冲
计算机外设
2501_924064114 小时前
2025年移动应用渗透测试流程方案及iOS安卓测试方法对比
android·ios
ACP广源盛139246256734 小时前
GSV2016@ACP#2016产品规格参数详解及产品应用场景分享
单片机·嵌入式硬件·计算机外设·音视频
ACP广源盛139246256734 小时前
GSV2501@ACP#2501产品规格参数详解及产品应用场景分享
单片机·嵌入式硬件·计算机外设·音视频
2501_9462429313 小时前
MPV-EASY Player (MPV播放器) v0.41.0.1
数据库·经验分享·云计算·计算机外设·github·电脑·csdn开发云
鼹鼠SDN18 小时前
【保姆教程】iPhone、iPad上玩电脑游戏 异地串流
ios·iphone·ipad·moonlight·sunshine·串流·科技数码
初级代码游戏19 小时前
iOS开发 SwiftUI 2 : Image
ios·swiftui·swift
TheNextByte120 小时前
如何在不使用 iCloud 的情况下备份 iPhone 短信
ios·iphone·icloud
denggun123451 天前
内存优化-(二)-oc&swift
ios·性能优化·cocoa·内存·swift