iOS键盘弹出 视图向上滚动键盘高度

来源:互联网 发布:vb直用颜色值 编辑:程序博客网 时间:2024/06/02 15:40

首先要对键盘添加监听:
在viewDidLoad中添加如下代码:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];
当系统消息出现UIKeyboardWillShowNotification和UIKeyboardWillHideNotification消息就会调用我们的keyboardWillAppear和keyboardWillDisappear方法。

其次键盘的高度计算:
-(CGFloat)keyboardEndingFrameHeight:(NSDictionary *)userInfo//计算键盘的高度
{
CGRect keyboardEndingUncorrectedFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
CGRect keyboardEndingFrame = [self.view convertRect:keyboardEndingUncorrectedFrame fromView:nil];
return keyboardEndingFrame.size.height;
}

传入的(NSDictionary *)userInfo用于存放键盘的各种信息,其中UIKeyboardFrameEndUserInfoKey对应的存放键盘的尺寸信息,以CGRect形式取出。

// 将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;
}

0 0
原创粉丝点击