Created
December 4, 2014 20:02
-
-
Save lborsato/6f34b87237140bbb5275 to your computer and use it in GitHub Desktop.
iOS UITextField Delegate methods to animate view frames up and down on keyboard appearance/disappearance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma mark - Text Editing functions | |
- (BOOL)textFieldShouldReturn:(UITextField *)textField | |
{ | |
[textField resignFirstResponder]; | |
return YES; | |
} | |
- (void)textFieldDidEndEditing:(UITextField *)textField | |
{ | |
CGRect viewFrame = self.frame; | |
viewFrame.origin.y += animatedDistance; | |
[UIView beginAnimations:nil context:NULL]; | |
[UIView setAnimationBeginsFromCurrentState:YES]; | |
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION]; | |
self.frame = viewFrame; | |
[UIView commitAnimations]; | |
} | |
- (void) textFieldDidBeginEditing:(UITextField*) textField { | |
CGRect textFieldRect = [self.window convertRect:textField.bounds fromView:textField]; | |
CGRect viewRect = [self.window convertRect:self.bounds fromView:self]; | |
CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height; | |
CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height; | |
CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height; | |
CGFloat heightFraction = numerator / denominator; | |
if (heightFraction < 0.0) { | |
heightFraction = 0.0; | |
} else if (heightFraction > 1.0) { | |
heightFraction = 1.0; | |
} | |
animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction); | |
CGRect viewFrame = self.frame; | |
viewFrame.origin.y -= animatedDistance; | |
[UIView beginAnimations:nil context:NULL]; | |
[UIView setAnimationBeginsFromCurrentState:YES]; | |
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION]; | |
self.frame = viewFrame; | |
[UIView commitAnimations]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment