添加鍵盤彈起和收起的監聽
1.監聽鍵盤的通知
- (void)viewWillAppear:(BOOL)animated {
? ? [super viewWillAppear:animated];
? ? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
? ? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
? ? [super viewWillDisappear:animated];
? ? [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
? ? [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
2.textfiled的代理方法,獲取點擊的是那個view
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
? ? self.tmpView = (InputView *)textField.superview;
? ? return YES;
}
3.鍵盤彈出的方法
- (void)keyBoardDidShow:(NSNotification *)notification {
? ? CGRect rect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 打印結構體的方法
//? ? NSLog(@"%@", NSStringFromCGRect(rect));
? ? CGFloat kbHeight = rect.size.height;
? ? CGFloat offset = (_tmpView.frame.origin.y + _tmpView.frame.size.height + 40 + _backScrollView.frame.origin.y) - (self.view.frame.size.height - kbHeight);
? ? double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
? ? if(offset > 0) {
? ? ? ? [UIView animateWithDuration:duration animations:^{
? ? ? ? ? ? self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
? ? ? ? }];
? ? }
}
4.鍵盤回收的方法
- (void)keyBoardDidHide:(NSNotification *)notif {
? ? double duration = [[notif.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
? ? [UIView animateWithDuration:duration animations:^{
? ? ? ? self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
? ? }];
}