经常会用到在键盘弹出或消失的时候做一些相应处理,比如视图上下偏移来自适应,所以我们获取这个事件以及键盘的高度。

#pragma mark - 键盘监听
- (void)addKeyboardNotifaction{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];//键盘将要显示
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];//键盘将要消失
}
#pragma mark - 键盘将要出现
- (void)keyboardWillShow:(NSNotification *)notification{
//获取键盘的高度
NSDictionary *userInfo = [notification userInfo];
NSValue *keyboardValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [keyboardValue CGRectValue];
CGFloat height = CGRectGetHeight(keyboardRect);
//做自定义事件
}
#pragma mark - 键盘将要消失
- (void)keyboardWillHide:(NSNotification *)notification{
//获取键盘的高度
NSDictionary *userInfo = [notification userInfo];
NSValue *keyboardValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [keyboardValue CGRectValue];
CGFloat height = CGRectGetHeight(keyboardRect);
//做自定义事件
}