监听键盘的通知
//增加监听,当键盘出现或改变时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
//增加监听,当键退出时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
通过通知方法获取键盘Rect 跟 Duration
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)note
{
//取出键盘最终的frame
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//取出键盘弹出需要花费的时间
double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
}
当滚动tableview时,就收起键盘:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//方式一
[self.view endEditing:YES];
//方式二:用textField
[self.textField endEditing:YES];
//方式三:
[self.textField resignFirstResponder];
}
不同过代码,在StoryBoard设置当滚动tableView隐藏键盘
当viewcontroller销毁时,需要移除这个通知监听
// 移除通知
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}