注册监听键盘事件的通知

时间:2022-07-10 20:30:35
注册监听键盘事件的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardDidHideNotification object:nil];

 

 

 

 在键盘将要出现和隐藏的回调中

- (void)keyboardWillShows:(NSNotification *)notif

{

    CGRect frame = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

 

    CGFloat  offset= -frame.size.height;

 

    [UIView animateWithDuration:0.3 animations:^{

        CGRect  rect  =self.frame;

       

        rect.origin.y=offset;

       

        self.frame=rect;

       

    }];

 

}

 

 

- (void)keyboardWillHides:(NSNotification *)notif

{

 

   

    [UIView animateWithDuration:0.3 animations:^{

        CGRect  rect  =self.frame;

       

        rect.origin.y=0;

       

        self.frame=rect;

        

    }];