iOS 中获得键盘的弹出和隐藏

来源:互联网 发布:淘宝开的店铺怎么关闭 编辑:程序博客网 时间:2024/05/17 01:42

1、首先在.h 中定义属性: keyBoardlsVisible 键盘的状态,键盘弹出其值为 YES ,键盘隐藏为NO,可通过状态的值进行自己相应的操作

{//  声明属性 .h 文件中@property(nonatomic,assign)BOOL keyBoardlsVisible;}

2、.m 中定义两个监测键盘状态的通知:keyboardDidShow、keyboardDidHide两个键盘状态的方法。通过这两个方法来知道键盘的状态,并把_keyBoardlsVisible 的值设置为相应的值

//  注册键盘通知方法- (void)registerNotification{    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];    [center addObserver:self selector:@selector(keyboardDidShow) name:UIKeyboardDidShowNotification object:nil];    [center addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardWillHideNotification object:nil];[center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];//  给keyBoardlsVisible赋初值    keyBoardlsVisible = NO;}


3、实现 keyboardDidShow和keyboardDidHide 两个方法

//  键盘弹出触发该方法- (void)keyboardDidShow{   NSLog(@"键盘弹出"); _keyBoardlsVisible = YES;}//  键盘隐藏触发该方法- (void)keyboardDidHide{   NSLog(@"键盘隐藏");    _keyBoardlsVisible =NO;}
/** * 键盘的frame发生改变时调用(显示、隐藏等) */- (void)keyboardWillChangeFrame:(NSNotification *)notification{    NSDictionary *userInfo = notification.userInfo;    // 动画的持续时间    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];    // 键盘的frame    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];   }








0 0
原创粉丝点击