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