如何在键盘弹出的时候视图或者输入框上移避免遮挡

监听键盘的弹出

为了避免键盘遮挡住输入框或者上方的视图

需要监听键盘的弹出

实现原理

首先 需要注册通知中心 当键盘的frame改变的时候 触发通知的方法

// 注册键盘的通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

- (void)keyboardWillChangeFrame:(NSNotification*)note{

// 取出键盘动画的时间

CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

// 取得键盘最后的frame

CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

// 计算控制器的view需要平移的距离

CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;

// 执行动画

[UIView animateWithDuration:duration animations:^{

self.view.transform = CGAffineTransformMakeTranslation(0, transformY);

}];

}

最后要在销毁控制器的时候删除删除通知

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

切记 ,通知有注册就有删除, 是一一对应的

完美

以上

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容