当界面上需要弹出键盘时,首先要注册通知监听器。
通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(Observer)
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
observer:监听器,即谁要接收这个通知
aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知
anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知
- (void)viewDidLoad {
[super viewDidLoad];
// 监听键盘通知
//弹出键盘通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//收起键盘通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//其实以上两个通知,键盘的弹出和隐藏用一个通知可以代替
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
#pragma mark - 键盘处理
- (void)keyboardWillChangeFrame:(NSNotification *)note {
//取出键盘最终的frame
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//取出键盘弹出需要花费的时间
double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//修改约束
//屏幕高度 - 键盘的Y值
self.bottomSpace.constant = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
- (void)keyboardWillShow:(NSNotification *)note {
//取出键盘最终的frame
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//取出键盘弹出需要花费的时间
double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//修改约束
self.bottomSpace.constant = rect.size.height;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
- (void)keyboardWillHide:(NSNotification *)note {
//取出键盘弹出需要花费的时间
double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//修改约束
self.bottomSpace.constant = 0;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
当滚动tableview时,就收起键盘:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//方式一
[self.view endEditing:YES];
//方式二:用textField
[self.textField endEditing:YES];
//方式三:
[self.textField resignFirstResponder];
}
当viewcontroller销毁时,需要移除这个通知监听:
- (void)dealloc {
//移除通知监听
[[NSNotificationCenter defaultCenter]removeObserver:self];
}