當界面上須要彈出鍵盤時,首先要註冊通知監聽器。web
通知中心(NSNotificationCenter)提供了方法來註冊一個監聽通知的監聽器(Observer)ide
- (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時,就收起鍵盤:code
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { //方式一 [self.view endEditing:YES]; //方式二:用textField [self.textField endEditing:YES]; //方式三: [self.textField resignFirstResponder]; }
當viewcontroller銷燬時,須要移除這個通知監聽:orm
- (void)dealloc { //移除通知監聽 [[NSNotificationCenter defaultCenter]removeObserver:self]; }