在开发IOS项目时计算键盘的高度

来源:互联网 发布:局域网数据流量监控 编辑:程序博客网 时间:2024/06/06 01:22

在IOS项目开发过程中,有时候需要计算键盘的高度,通过键盘的高度去动态的显示一些需要用到键盘的控件。比如在输入密码和用户名时,为了不让弹出的键盘遮挡密码和用户名输入框,需要计算键盘的高度去改变输入框控件的位置。

以下是实现代码:

//可以在viewDidLoad方法中,也可以在需要弹出键盘的代码中,视具体情况而定!

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    //增加监听,当键盘出现或改变时收出消息

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(keyboardDidShow:)

                                                 name:UIKeyboardWillShowNotification

                                               object:nil];

    

    //增加监听,当键退出时收出消息

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(keyboardDidHide:)

                                                 name:UIKeyboardWillHideNotification

                                               object:nil];

    

    

}


//当键盘出现或改变时调用

- (void)keyboardDidShow:(NSNotification *)aNotification

{

    //获取键盘的高度

    NSDictionary *userInfo = [aNotification userInfo];

    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = [aValue CGRectValue];

    int height = keyboardRect.size.height;

}


//当键退出时调用

- (void)keyboardDidHide:(NSNotification *)aNotification

{

    NSLog(@"-----键盘隐藏!------");

}

0 0