Created
June 24, 2014 13:19
-
-
Save insanoid/7d53b7500f1e7b31f02d to your computer and use it in GitHub Desktop.
Keyboard View Handling
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
//H File should have | |
//CGFloat animatedDistance; | |
const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3; | |
const CGFloat MINIMUM_SCROLL_FRACTION = 0.2; | |
const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8; | |
const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216; | |
const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162; | |
#pragma mark - TextField Delegate | |
- (BOOL)textFieldShouldReturn:(UITextField *)textField { | |
[textField resignFirstResponder]; | |
return YES; | |
} | |
-(void) textFieldDidBeginEditing:(UITextField *)textField { | |
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) | |
{ | |
CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField]; | |
CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view]; | |
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; | |
} | |
UIInterfaceOrientation orientation = | |
[[UIApplication sharedApplication] statusBarOrientation]; | |
if (orientation == UIInterfaceOrientationPortrait) | |
{ | |
animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction); | |
} | |
else | |
{ | |
animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction); | |
} | |
CGRect viewFrame = self.view.frame; | |
viewFrame.origin.y -= animatedDistance; | |
[UIView beginAnimations:nil context:NULL]; | |
[UIView setAnimationBeginsFromCurrentState:YES]; | |
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION]; | |
[self.view setFrame:viewFrame]; | |
[UIView commitAnimations]; | |
} | |
} | |
-(void) textFieldDidEndEditing:(UITextField *)textField { | |
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) | |
{ | |
CGRect viewFrame = self.view.frame; | |
viewFrame.origin.y += animatedDistance; | |
[UIView beginAnimations:nil context:NULL]; | |
[UIView setAnimationBeginsFromCurrentState:YES]; | |
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION]; | |
[self.view setFrame:viewFrame]; | |
[UIView commitAnimations]; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment