-(void)viewWillAppear:(BOOL)animated{
[self scrollTableViewToBottomAnimate:NO];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
-(void)scrollTableViewToBottomAnimate:(BOOL)animate{
if (self.messages.count >0) {
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0 ] atScrollPosition:UITableViewScrollPositionBottom animated:animate];
}
}
-(void)keyboardWillShow:(NSNotification *)aNotification{
[self handleKeyboardShowAndHide:aNotification];
}
-(void)keyboardWillHide:(NSNotification *)aNotification{
[self handleKeyboardShowAndHide:aNotification];
}
-(void)handleKeyboardShowAndHide:(NSNotification *)aNotification{
CGRect keyboardRect = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
CGRect beforeFrame = self.imView.frame;
CGFloat keyboardY = [self.view convertRect:keyboardRect fromView:nil].origin.y;
self.imView.frame = CGRectMake(beforeFrame.origin.x, keyboardY-beforeFrame.size.height, beforeFrame.size.width, beforeFrame.size.height);
}];
}