第一步,註冊Keyboard通知(在ViewDidLoad中或者viewWillAppear中註冊)
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardDidChangeFrame:)name:UIKeyboardDidChangeFrameNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];
第二步,實現通知方法
- (void)keyboardWillShow:(NSNotification *)notification
{
NSDictionary* info = [notificationuserInfo];
kbSize = [[infoobjectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size;
NSLog(@"%lf",kbSize.height);
}
- (void)keyboardDidChangeFrame:(NSNotification *)notification
{
NSDictionary* info = [notificationuserInfo];
CGRect kbRect = [[infoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
kbSize = [[infoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
NSLog(@"%lf",kbSize.height);
if (self.view.origin.y<0) {
return;
}
if (kbRect.origin.y >=ViewHeight) {
return;
}
self.bottomView.top =ViewHeight-kbSize.height-self.bottomView.height;
[self.viewaddSubview:self.bottomView]; //這裏的self.bottomView就是放UITextfiled的一個視圖
//這是在另一個控制器裏面根據實際視圖效果計算的高度
// kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//
// UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height-44, 0.0);
// self.tableView.scrollEnabled = YES;
// self.tableView.contentInset = contentInsets;
// self.tableView.scrollIndicatorInsets = contentInsets;
// NSLog(@"keyboardWasShown");
//
//// If active text field is hidden by keyboard, scroll it so it's visible
//// Your application might not need or want this behavior.
// CGRect aRect = self.view.frame;
// aRect.size.height -= kbSize.height;
// BigBeautyCircleViewCell *cell = [[BigBeautyCircleViewCell alloc] init];
// if (!CGRectContainsPoint(aRect, cell.bottomView.commentFiled.superview.superview.frame.origin) ) {
// CGPoint scrollPoint = CGPointMake(0.0, cell.bottomView.commentFiled.superview.superview.frame.origin.y-aRect.size.height+44);
// [self.tableView setContentOffset:scrollPoint animated:YES];
// }
}
- (void)keyboardWillHide:(NSNotification *)notification
{
self.bottomView.bottom =ViewHeight;
[self.viewaddSubview:self.bottomView];
}
第三步,移除通知(在dealloc或者viewWillDisappear中移除)
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardDidChangeFrameNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillHideNotificationobject:nil];