键盘监听

133 阅读1分钟
#pragma mark **- --- 3.4 键盘通知事件 ---**

- (void)addObserverKeyboardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeObserverKeyboardNotification {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)noti {
    CGRect rect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = rect.size.height;
    CGPoint center = self.center;
    center.y -= height/2;
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.center = center;
    }];
}

- (void)keyboardWillHide:(NSNotification *)noti {
    CGPoint center = self.center;
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.center = center;
    }];
}