1.添加监听键盘的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2.实现方法
/**
* 键盘即将显示的时候调用
*/
- (void)keyboardWillShow:(NSNotification *)note
{
// 1.取出键盘的frame
CGRect begin = [note.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect end = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 2.取出键盘弹出的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//3.输入框弹起后的Y
CGFloat y_board = 0;
//4.处理键盘(包括第三方键盘)
if(begin.size.height > 0 && (begin.origin.y - end.origin.y > 0)){
//处理逻辑
y_board = end.origin.y - self.view_comment.frame.size.height;
[UIView animateWithDuration:duration animations:^{
self.view_comment.transform = CGAffineTransformMakeTranslation(0, -end.size.height);
//5.让tableView上移
if (self.tableView.contentSize.height >= y_board - self.view_comment.frame.size.height)//tableview内容的高度 > 键盘上面工具栏的Y
{
self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height + end.size.height + self.view_comment.frame.size.height);
}
else if (self.tableView.contentSize.height + 80 >= y_board - self.view_comment.frame.size.height)
{
self.tableView.contentOffset = CGPointMake(0, 80 - (y_board - self.view_comment.frame.size.height - self.tableView.contentSize.height));
} else
{
self.tableView.contentOffset = CGPointMake(0, 0);
}
}];
}
}
/**
* 键盘即将退出的时候调用
*/
- (void)keyboardWillHide:(NSNotification *)note
{
// 1.取出键盘弹出的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 2.执行动画
[UIView animateWithDuration:duration animations:^{
//如果高度超过了本身高度,要让最后一个cell在底部
[self scrollToRow];
self.view_comment.transform = CGAffineTransformIdentity;
}];
}
- (void)scrollToRow
{
if (self.tableView.contentSize.height <= self.tableView.frame.size.height) {
self.tableView.contentOffset = CGPointMake(0, 0);
} else {
self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
}
}