代码改变世界

ios ---键盘的监听事件

2014-07-29 20:53  立志成为大神  阅读(835)  评论(0编辑  收藏  举报

//在view将要出现的时候重载viewWillAppear方法添加通知 监听事件 keyboardWillShow:  keyboardWillHide:

- (void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(keyboardWillShow:)

                                                 name:UIKeyboardWillShowNotification

                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(keyboardWillHide:)

                                                 name:UIKeyboardWillHideNotification

                                               object:nil];

}

//当你页面跳转后,要移除两个通知  因为通知不移除,会一直存在在内存中

- (void) viewDidDisappear:(BOOL)paramAnimated {

    [super viewDidDisappear:paramAnimated];

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

//实现监听事件的两个方法

- (void)keyboardWillShow:(NSNotification *)note {

 

//获取键盘的高度

//通知消息 NSNotification中的 userInfo字典中包含键盘的位置和大小信息,对应的key为

//UIKeyboardFrameBeginUserInfoKey
//UIKeyboardFrameEndUserInfoKey

//对应的Value是个NSValue对象,内部包含CGRect结构,分别为键盘起始时和终止时的位置信息。
//UIKeyboardAnimationDurationUserInfoKey

对应的Value也是NSNumber对象,内部为double类型的数据,表示键盘h显示或消失时动画的持续时间。
//UIKeyboardAnimationCurveUserInfoKey

//对应的Value是NSNumber对象,内部为UIViewAnimationCurve类型的数据,表示键盘显示或消失的动画类型。

// UIKeyboardFrameEndUserInfoKey   动画前键盘的位置,包含CGRect的NSValue

//UIKeyboardFrameEndUserInfoKey    动画结束后的键盘位置,包含CGRect的NSValue

 

//NSDictionary* info = [aNotification userInfo];  

//CGRect _rect  =[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 

//note.info[objectForKey:UIKeyboardFrameEndUserInfoKey]

    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    CGFloat deltaY=keyBoardRect.size.height;

 

    [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{

          self.view.transform=CGAffineTransformMakeTranslation(0, -deltaY);

    }];

 

}

 

- (void)keyboardWillHide:(NSNotification *)note {

    [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{

 

//    CGAffineTransformIdentity 记录先前的位置

//    CGAffineTransformMakeTranslation : 每次都是以最初位置的中心点为参考

//    CGAffineTransformTranslate 每次都是以传入的transform为参照(既 有叠加效果)

//    CGAffineTransformIdentity  最初位置的中心点

       self.view.transform = CGAffineTransformIdentity;

    }];

}