您的位置:首页 > 移动开发 > IOS开发

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

2016-11-02 09:01 381 查看
首先要对键盘添加监听:

在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所在视图转换到
effa
目标视图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;

}

-(void)dealloc

{

    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: