View isn't scrolling back down after I dismiss the keyboard
- by fmi
I have a Tab Bar app. One of the views has a UITextView that is hidden by the keyboard when touched. I've set the view to scroll to account for the keyboard but it the view doesn't always return to it's original position after I dismiss the keyboard. Here is my code:
//Scroll the view for keyboard
- (void)viewWillAppear:(BOOL)animated {
void (^keyBoardWillShow) (NSNotification *)= ^(NSNotification * notif) {
NSDictionary* info = [notif userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
float bottomPoint = (additionalView.frame.origin.y + additionalView.frame.size.height + 10);
scrollAmount = keyboardSize.height - (self.view.frame.size.height - bottomPoint);
if (scrollAmount > 0) {
moveViewUp =YES;
[self scrollTheView:YES];
}
else
moveViewUp = NO;
};
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:self.view.window queue:nil
usingBlock:keyBoardWillShow];
void (^keyBoardWillHide) (NSNotification *)= ^(NSNotification * notif) {
if (moveViewUp) [self scrollTheView:NO];
};
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:self.view.window queue:nil
usingBlock:keyBoardWillHide];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[super viewWillDisappear:animated];
}
(void)scrollTheView:(BOOL)movedUp {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGRect rect = self.view.frame;
if (movedUp){
rect.origin.y -= scrollAmount;
}
else {
rect.origin.y += scrollAmount;
}
self.view.frame = rect;
[UIView commitAnimations];
}