首先要对键盘添加监听:
在viewDidLoad中添加如下代码:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];
当系统消息出现UIKeyboardWillShowNotifi
其次键盘的高度计算:
-(CGFloat)keyboardEndingFrameHeight:(NSDictionary *)userInfo//计算键盘的高度
{
CGRect keyboardEndingUncorrectedFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
CGRect keyboardEndingFrame = [self.view convertRect:keyboardEndingUncorrectedFrame fromView:nil];
return keyboardEndingFrame.size.height;
}
传入的(NSDictionary *)userInfo用于存放键盘的各种信息,其中UIKeyboardFrameEndUserIn
// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
// 将rect从view中转换到当前视图中,返回在当前视图中的rect
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
最终返回的是键盘在当前视图中的高度。
然后,根据键盘高度将当前视图向上滚动同样高度。
-(void)keyboardWillAppear:(NSNotification *)notification
{
CGRect currentFrame = self.view.frame;
CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
currentFrame.origin.y = currentFrame.origin.y - change ;
self.view.frame = currentFrame;
}
最后,当键盘消失后,视图需要恢复原状。
-(void)keyboardWillDisappear:(NSNotification *)notification
{
CGRect currentFrame = self.view.frame;
CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
currentFrame.origin.y = currentFrame.origin.y + change ;
self.view.frame = currentFrame;
}
参考:http://blog.sina.com.cn/s/blog_6386ae0d0102v5i7.html
http://hchen229.iteye.com/blog/1099707
http://www.cnblogs.com/zhulin/archive/2011/10/15/2213687.html