设置视图随着键盘的弹出收起来上移还原

首先是效果图:


gif

实现原理:

// 注册键盘的通知

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

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

//设置窗口的颜色

self.view.window.backgroundColor = self.view.backgroundColor;

// 取出键盘动画的时间

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);

}];

}

// 点击view收起键盘

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event

{

[self.view endEditing:YES];

}

// 最后别忘了在销毁控制器的时候删除通知

- (void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容