zoukankan      html  css  js  c++  java
  • [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(即键盘的父视图),可以完成在键盘上加控件。

  • 相关阅读:
    IIS中ASP.NET安全配置
    好用的SQLSERVER数据库自动备份工具SQLBackupAndFTP(功能全面)
    js取两位小数点
    json格式的ajax传输交互
    js全选与反选
    formdata,ajax提交数据
    js判断是否微信浏览器、IE浏览器
    js实现列表从下往上循环滚动
    绝对定位始终居中
    存储、字符串截取、两端对齐、样式绑定、微信调拨号功能
  • 原文地址:https://www.cnblogs.com/shisishao/p/5784859.html
Copyright © 2011-2022 走看看