[iOS]关于动态获取键盘高度,及在键盘上添加按钮或控件方法

iOS开发中,在布局界面时,有时要考虑键盘弹出和收回的问题,来动态改变界面的布局,这时就要获取键盘的高度,但是我们知道iOS的键盘有多种样式,不同的键盘样式高度不一样,而且不同的iOS版本,键盘高度也有所区别,所以肯定不能认为键盘高度是个固定值,这是就要去获取当前弹出的键盘高度,再来改变界面控件的frame,这里提供了一种获取键盘高度的方法,并且能监听到,键盘弹出和收回的动作,不多说,直接上代码:

- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

}

- (void)keyboardWillShow:(NSNotification *)aNotification {
    NSDictionary *userInfo = aNotification.userInfo;
    NSValue *endFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardEndFrame = [self.view convertRect:endFrameValue.CGRectValue fromView:nil];  // 键盘的frame
  // 接下拉可以在动画内来改变界面的布局,布局会随着键盘弹出,平滑的过度
    [UIView animateWithDuration:0.23f
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         __strong typeof (weakSelf)strongSelf = weakSelf;
                         NSInteger count = [[UIApplication sharedApplication] windows].count;
                         if (count > 1) {
                  // 获取到键盘的父视图 (UIWindow),这时可在键盘的父视图上添加一个按钮或者自定义控件
                             UIWindow *tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
                             [tempWindow addSubview:strongSelf->customButton];
                         }
                     }
                     completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)aNotification {
     [UIView animateWithDuration:0.23f
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         __strong typeof (weakSelf)strongSelf = weakSelf;

                         // 动画内恢复控件布局
                     }
                     completion:nil];

}

 

我们知道,键盘是弹在window 上的,所以要想在键盘上添加一个按钮或者控件,可以先找到键盘所在父视图,然后把控件加在键盘的父视图,调整相应的frame即可,这里,在弹出键盘的监听方法中,给出了键盘所在window(即键盘的父视图),可以完成在键盘上加控件。

 

posted @ 2016-08-18 17:52  小码哥伍六七  阅读(1019)  评论(0编辑  收藏  举报