iPhone Keyboard Covers UITextField
The usual solution is to slide the field (and everything above it) up with an animation, and then back down when you are done. You may need to put the text field and some of the other items into another view and slide the view as a unit. (I call these things "plates" as in "tectonic plates", but that's just me). But here is the general idea if you don't need to get fancy.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField: textField up: YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField: textField up: NO];
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 80; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
IQKeyboardManager do this for you with NO LINE OF CODE, only need to drag and drop related source file to project. IQKeyboardManager also support Device Orientation, Automatic UIToolbar Management, keyboardDistanceFromTextField and much more than you think.
Here is the Control Flow Chart:
Step1:- Added global notifications of UITextField
, UITextView
, and UIKeyboard
in a singleton class. I called it IQKeyboardManager.
Step2:- If found UIKeyboardWillShowNotification
, UITextFieldTextDidBeginEditingNotification
or UITextViewTextDidBeginEditingNotification
notifications, then try to get topMostViewController
instance from the UIWindow.rootViewController
hierarchy. In order to properly uncover UITextField
/UITextView
on it, topMostViewController.view
's frame needs to be adjusted.
Step3:- Calculated expected move distance of topMostViewController.view
with respect to first responded UITextField
/UITextView
.
Step4:- Moved topMostViewController.view.frame
up/down according to the expected move distance.
Step5:- If found UIKeyboardWillHideNotification
, UITextFieldTextDidEndEditingNotification
or UITextViewTextDidEndEditingNotification
notification, then again try to get topMostViewController
instance from the UIWindow.rootViewController
hierarchy.
Step6:- Calculated disturbed distance of topMostViewController.view
which needs to be restored to it's original position.
Step7:- Restored topMostViewController.view.frame
down according to the disturbed distance.
Step8:- Instantiated singleton IQKeyboardManager class instance on app load, so every UITextField
/UITextView
in the app will adjust automatically according to the expected move distance.
That's all
This worked wonders for me sliding uitextfields
In particular it has the benefit of calculating the slide animation distance depending on the position of the text field.