首先是效果图:
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];
}