OC textField鍵盤彈起事件
經常用到點擊textFiled時彈起鍵盤,然后 textField工具條也要隨之上升,自己做了個簡單的例子
1. 監聽鍵盤彈起收回事件
//監聽鍵盤彈出事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//監聽鍵盤隱藏事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2. 實現對應方法
獲取鍵盤的高度時一定要用** objectForKey:UIKeyboardFrameEndUserInfoKey**,切記
#pragma mark - 鍵盤即將彈出事件處理
- (void)keyboardWillShow:(NSNotification *)notification
{
//獲取鍵盤信息
NSDictionary *keyBoardInfo = [notification userInfo];
//獲取動畫時間
CGFloat duration = [[keyBoardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//獲取鍵盤的frame信息
NSValue *value = [keyBoardInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
[UIView animateWithDuration:duration animations:^{
CGRect frame = _chatBar.frame;
frame.origin.y = SCREENHEIGHT - keyboardSize.height - frame.size.height;
_chatBar.frame = frame;
} completion:nil];
}
#pragma mark - 鍵盤即將隱藏事件
- (void)keyboardWillHide:(NSNotification *)notification
{
//獲取鍵盤信息
NSDictionary *keyBoardInfo = [notification userInfo];
//獲取動畫時間
CGFloat duration = [[keyBoardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//獲取鍵盤的frame信息
[UIView animateWithDuration:duration animations:^{
CGRect frame = _chatBar.frame;
frame.origin.y = SCREENHEIGHT - _chatBar.height;
_chatBar.frame = frame;
} completion:nil];
}