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];
}
相关推荐
wn5311 天前
【浏览器 - Mac实时调试iOS手机浏览器页面】
前端·macos·ios·智能手机·浏览器
小鹿撞出了脑震荡2 天前
Effective Objective-C 2.0 读书笔记—— 方法调配(method swizzling)
ios·objective-c·swift
小鹿撞出了脑震荡2 天前
Effective Objective-C 2.0 读书笔记—— 消息转发
ios·objective-c·swift
一丝晨光3 天前
Cocoa和Cocoa Touch是什么语言写成的?什么是Cocoa?编程语言中什么是框架?为什么苹果公司Cocoa类库有不少NS前缀?Swift编程语言?
macos·ios·objective-c·cocoa·swift·uikit·cocoa touch
小马不是哥哥3 天前
护眼好帮手:Windows显示器调节工具
计算机外设
凯明哲3 天前
联想拯救者R720笔记本外接显示屏方法,显示屏是2K屏27英寸
计算机外设
蚂蚁不吃土&4 天前
笔记本搭配显示器
计算机外设
ljm12004 天前
DIY QMK量子键盘
计算机外设
心语明洲6 天前
实现GD32F470作为高速USB主机与USB鼠标通信的功能
stm32·单片机·计算机外设
LucianaiB6 天前
字节iOS面试经验分享:HTTP与网络编程
网络·ios·面试