Set UITextView on full screen in ios - ios

I have set a UITextView on full screen of device like in iphone-5s,textView size is (0,44,320,524). when keyboard appear then user cant show the insert text in view.how can I manage the UITextView, can i use UIScrollView for it or any thing else?

While editing complete View will move up and after done editing will move down...
(void)textViewDidBeginEditing:(UITextView *)textView {
[self animateTextView: YES];
}
(void)textViewDidEndEditing:(UITextView *)textView {
  [self animateTextView:NO];
}
(void) animateTextView:(BOOL) up {
const int movementDistance =heightKeyboard; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement= movement = (up ? -movementDistance : movementDistance);
NSLog(#"%d",movement);
[UIView beginAnimations: #"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
[UIView commitAnimations];
}
I hope it will work for you.

I have solved it by using this code
.h file define a value
CGRect originalTextViewFrame;
.m file
- (void)viewWillAppear:(BOOL)animated
{
// Register notifications for when the keyboard appears
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)keyboardWillShow:(NSNotification*)notification
{
[self moveTextViewForKeyboard:notification up:YES];
}
- (void)keyboardWillHide:(NSNotification*)notification
{
[self moveTextViewForKeyboard:notification up:NO];
}
- (void)moveTextViewForKeyboard:(NSNotification*)notification up:(BOOL)up
{
NSDictionary *userInfo = [notification userInfo];
NSTimeInterval animationDuration;
UIViewAnimationCurve animationCurve;
CGRect keyboardRect;
[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
[UIView beginAnimations:#"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
[UIView setAnimationCurve:animationCurve];
if (up == YES) {
CGFloat keyboardTop = keyboardRect.origin.y;
CGRect newTextViewFrame = textView.frame;
originalTextViewFrame = textView.frame;
newTextViewFrame.size.height = keyboardTop - textView.frame.origin.y - 10;
textView.frame = newTextViewFrame;
}
else
{
// Keyboard is going away (down) - restore original frame
textView.frame = originalTextViewFrame;
}
[UIView commitAnimations];
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// Any new character added is passed in as the "text" parameter
if ([text isEqualToString:#"\n"])
{
// Be sure to test for equality using the "isEqualToString" message
[textView resignFirstResponder];
//[scrlView setContentOffset:CGPointMake(0,0) animated:YES];
// Return FALSE so that the final '\n' character doesn't get added
return FALSE;
}
// For any other character return TRUE so that the text gets added to the view
return TRUE;
}

use scroll view and then after try
UITextViewDelegate
method
- (void)textViewDidBeginEditing:(UITextView *)textView
{
[scrollView setContentOffset:CGPointMake(0,yourtextview.center.y-200) animated:YES];
}

Related

Obj-c - Delayed animation when returning to original state?

I'm using the below code to shift a view and my tableview up when my keyboard is activated. When the keyboard is closed however, it takes the upView a solid 2 seconds after the keyboard closes to return to where it was (the tableView on the other hand, is instant). Why is this happening?
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillChange:) name:UIKeyboardWillShowNotification object:nil];
}
- (void)keyboardWillChange:(NSNotification *)notification {
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
UITabBarController *tabBarController = [UITabBarController new];
CGFloat tabBarHeight = tabBarController.tabBar.frame.size.height;
self.keyboardHeight = keyboardFrameBeginRect.size.height - tabBarHeight;
}
- (void) animateTextView:(BOOL) up
{
const int movementDistance = self.keyboardHeight;
const float movementDuration = 0.2f;
int movement= movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: #"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.upView.frame = CGRectOffset(self.upView.frame, 0, movement);
[UIView setAnimationDidStopSelector:#selector(afterAnimationStops)];
[UIView commitAnimations];
self.tableView.frame = CGRectOffset(self.tableView.frame, 0, movement);
[UIView setAnimationDidStopSelector:#selector(afterAnimationStops)];
[UIView commitAnimations];
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
[self animateTextView:YES];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
[self animateTextView:NO];
}
UPDATED CODE
.m
- (void)handleKeyboard:(NSNotification*)aNotification{
NSDictionary* info = [aNotification userInfo];
NSValue* value = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval duration = 3;
[value getValue:&duration];
if (aNotification.name == UIKeyboardWillHideNotification) {
/** KEYBOARD HIDE **/
[UIView animateWithDuration:0 animations:^{ self.upView.frame = CGRectOffset(self.upView.frame, 0, self.keyboardHeight); self.tableView.frame = CGRectOffset(self.tableView.frame, 0, self.keyboardHeight); } completion:^(BOOL finished) {}];
[self moveCustomView:NO duration:duration];
NSLog(#"CLOSED!");
}
if (aNotification.name == UIKeyboardWillShowNotification) {
/** KEYBOARD SHOW **/
[UIView animateWithDuration:0 animations:^{ self.upView.frame = CGRectOffset(self.upView.frame, 0, -self.keyboardHeight); self.tableView.frame = CGRectOffset(self.tableView.frame, 0, -self.keyboardHeight); } completion:^(BOOL finished) {}];
[self moveCustomView:YES duration:duration];
}
}
- (void)moveCustomView:(BOOL)move duration:(NSTimeInterval)time{
}
This issue might be with the animation duration, so you can get the keyboard showing and hiding animation duration from the -(void)handleKeyboard:(NSNotification *)notification {}
and also handle the showing and hiding your custom view inside the same function. Add the following code to your viewDidLoad function
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleKeyboard:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleKeyboard:) name:UIKeyboardWillShowNotification object:nil];
Handle keyboard actions and UI changes
- (void)handleKeyboard:(NSNotification*)aNotification{
NSDictionary* info = [aNotification userInfo];
NSValue* value = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval duration = 0;
[value getValue:&duration];
if (aNotification.name == UIKeyboardWillHideNotification) {
/** KEYBOARD HIDE **/
//calculate your view frames and handle UI changes
/*
.
.
.
.
.
*/
[self moveCustomView:NO duration:duration];
}
if (aNotification.name == UIKeyboardWillShowNotification) {
/** KEYBOARD SHOW **/
//calculate your view frames and handle UI changes
/*
.
.
.
.
.
*/
[self moveCustomView:YES duration:duration];
}
}
- (void)moveCustomView:(BOOL)move duration:(NSTimeInterval)time{
}
I think you need to use thread to call animation immediately...
- (void)textViewDidBeginEditing:(UITextView *)textView {
dispatch_async(dispatch_get_main_queue(), ^{
[self animateTextView:YES];
});
}
- (void)textViewDidEndEditing:(UITextView *)textView {
dispatch_async(dispatch_get_main_queue(), ^{
[self animateTextView:NO];
});
}
I'm not much aware of your problem, but try this because if we got this type of problems dispatch_async() will solve.

Keyboard move up and down with many subviews with uiTextfield

I need to move a keyboard up and down. I have many subviews with many uiTextfields. These subviews has one superview and this superview is in the scroll view.
I can't move up a view using below code:
- (void) keyboardWasShown:(NSNotification *)notification{
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0);
self.Scroll_view.contentInset = contentInsets;
self.Scroll_view.scrollIndicatorInsets = contentInsets;
}
- (void) keyboardWillBeHidden:(NSNotification *)notification{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.Scroll_view.contentInset = contentInsets;
self.Scroll_view.scrollIndicatorInsets = contentInsets;
}
This code working fine when i place all the UITextfields in the ScrollView(Not into the subviews), But i need to do with subview and also move keyboard up and down.
How can i move a keyboard up and down while press keyboard Next/Return key?
Try This:
- (void)animateViewUpToTargetYOrigin:(CGFloat)yValue
{
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardDidChangeFrameNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
CGFloat yOrigin = 0;
CGFloat keyboardYOrigin = [[[note userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
if (yValue > keyboardYOrigin) {
yOrigin = yValue - keyboardYOrigin;
}
[UIView animateWithDuration:0.3f animations:^{
self.view.frame = CGRectMake(self.frame.origin.x, -yOrigin, self.frame.size.width, self.frame.size.height);
}];
}];
Using this code you only need to call this method in textfield didbeginediting, and pass the yOrigin(textfield)+height(textField) as y value in it.
If you textFields are in Scrollview or any sub view convert their frame values in respect to self.view before sending Y value.
E.g:
CGRect textFieldRectWithRespectToSelfView = [textField.superview convertRect:textField.frame toView:self.view];
[self.view animateViewUpToTargetYOrigin: textFieldRectWithRespectToSelfView.orgin.y + textFieldRectWithRespectToSelfView.size.height];
When you call [textField resignFirstResponder], self.view comes back to its original position. This happens because the UIKeyboardDidChangeFrameNotification always keeps listening to keyboard frame changes.
I do have a demo project in github as an example please refer to it:
https://github.com/subhajitregor/ViewMoveUpExample
In viewDidLoad method
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
// the keyboard is hiding reset the table's height
NSTimeInterval animationDuration =
[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.view.frame;
frame.origin.y += 150;
[UIView beginAnimations:#"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
// the keyboard is showing so resize the table's height
NSTimeInterval animationDuration =
[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.view.frame;
frame.origin.y -= 150;
[UIView beginAnimations:#"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}

How to move View up when Keyboard come over the TextFields?

i am having 10 textfields over the scrollView. I want to scroll the view when keyboard Appears on Textfileds . Here i am using the below code to achieve this. But it is moving the screen up from the First Textfield my requirement is i want to move view up when keyboard come over the textfield only otherwise i don't want to move the view up.
Please help me.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGPoint scrollPoint = CGPointMake(0, textField.frame.origin.y);
[myScrollView setContentOffset:scrollPoint animated:YES];
}
Something like this maybe? (You may have to readapt it for landscape mode)
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGFloat keyboardHeight = 216.0;
CGFloat viewHeight = myScrollView.frame.size.height;
BOOL covering = (textField.frame.origin.y - myScrollView.contentOffset.y) > (viewHeight - keyboardHeight);
if(covering) {
CGPoint scrollPoint = CGPointMake(0, textField.frame.origin.y);
[myScrollView setContentOffset:scrollPoint animated:YES];
}
}
There are ready solutions for this.
You could use TPKeyboardAvoiding to accomplish your mission.
Use keyboard notifications to be alerted when the keyboard is presented e.g.:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
(Also remove these in viewWillDissapear:
[[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillShowNotification];
[[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillHideNotification];
Then in the functions respectively:
- (void)keyboardWillShow:(NSNotification *) notification {
CGRect appFrame = YOUR_VIEWS_FRAME
CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardFrame = [self.view.window convertRect:keyboardFrame toView:self.view];
UITextField *current = THE_CURRENT_RESPONDER
CGRect relativeFrame = [self.view convertRect:current.frame fromView:current.superview];
float difference = 0.0;
//Here we give it a 20 pixel padding between the top of the keyboard and the bottom of the text field.
if (CGRectIntersectsRect(relativeFrame, keyboardFrame))
difference = appFrame.size.height - keyboardFrame.size.height - 20 - relativeFrame.size.height - current.frame.origin.y;
difference = difference < 0 ? difference : 0;
NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
[self.scrolLView setContentOffset:CGPointMake(0, difference);
} completion:^(BOOL finished) {
}];
}
And:
- (void)keyboardWillHide:(NSNotification *) notification {
NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
[self.scrolLView setContentOffset:CGPointZero];
} completion:^(BOOL finished) {
}];
}

How to get the iOS default key board size [duplicate]

Is there some way to get UIKeyboard size programmatically. 216.0f height and 162.0f height in landscape.
Following seem to be deprecated. Is there some way that works without any warning in both 3.0 iPhone OS SDK and 4.0 iPhone OS SDK to do this..
CGSize keyBoardSize = [[[note userInfo]
objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
You can get the keyboard size from the userInfo dictionary using the UIKeyboardFrameBeginUserInfoKey and the UIKeyboardFrameEndUserInfoKey instead.
These two keys return a NSValue instance containing a CGRect that holds the position and size of the keyboard at both the start and end points of the keyboard's show/hide animation.
Edit:
To clarify, the userInfo dictionary comes from an NSNotification instance. It's passed to your method that you register with an observer. For example,
- (void)someMethodWhereYouSetUpYourObserver
{
// This could be in an init method.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myNotificationMethod:)
name:UIKeyboardDidShowNotification
object:nil];
}
- (void)myNotificationMethod:(NSNotification*)notification
{
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}
Edit 2:
Also, please don't forget to remove yourself as an observer in your dealloc method! This is to avoid a crash that would occur when the notification center tries to notify your object after its been freed.
You should use the UIKeyboardWillChangeFrameNotification instead, because some international keyboards, like the Chinese keyboard, will change frames during use. Also make sure to convert the CGRect into the proper view, for landscape use.
//some method like viewDidLoad, where you set up your observer.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
- (void)keyboardWillChange:(NSNotification *)notification {
CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; //this is it!
}
Here's how I finally made works. I combined suggestions and codes from different answers.
Features: dismissing keyboard, moving text fields above keyboard while editing and setting "Next" and "Done" keyboard return type.REPLACE "..." with more fields
static const CGFloat ANIMATION_DURATION = 0.4;
static const CGFloat LITTLE_SPACE = 5;
CGFloat animatedDistance;
CGSize keyboardSize;
#interface ViewController () <UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *firstNameTXT;
.....// some other text fields
#property (weak, nonatomic) IBOutlet UITextField *emailTXT;
#end
#implementation ViewController
- (void)viewDidLoad{
.....
// add tap gesture to help in dismissing keyboard
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(tapScreen:)];// outside textfields
[self.view addGestureRecognizer:tapGesture];
// set text fields return key type to Next, last text field to Done
[self.firstNameTXT setReturnKeyType:UIReturnKeyNext];
.....
[self.emailTXT setReturnKeyType:UIReturnKeyDone];
// set text fields tags
[self.firstNameTXT setTag:0];
....// more text fields
[self.emailTXT setTag:5];
// add keyboard notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}
// dismiss keyboard when tap outside text fields
- (IBAction)tapScreen:(UITapGestureRecognizer *)sender {
if([self.firstNameTXT isFirstResponder])[self.firstNameTXT resignFirstResponder];
...
if([self.emailTXT isFirstResponder])[self.emailTXT resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
if(textField.returnKeyType==UIReturnKeyNext) {
// find the text field with next tag
UIView *next = [[textField superview] viewWithTag:textField.tag+1];
[next becomeFirstResponder];
} else if (textField.returnKeyType==UIReturnKeyDone || textField.returnKeyType==UIReturnKeyDefault) {
[textField resignFirstResponder];
}
return YES;
}
// Moving current text field above keyboard
-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField{
CGRect viewFrame = self.view.frame;
CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
CGFloat textFieldBottomLine = textFieldRect.origin.y + textFieldRect.size.height + LITTLE_SPACE;//
CGFloat keyboardHeight = keyboardSize.height;
BOOL isTextFieldHidden = textFieldBottomLine > (viewRect.size.height - keyboardHeight)? TRUE :FALSE;
if (isTextFieldHidden) {
animatedDistance = textFieldBottomLine - (viewRect.size.height - keyboardHeight) ;
viewFrame.origin.y -= animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
return YES;
}
-(void) restoreViewFrameOrigionYToZero{
CGRect viewFrame = self.view.frame;
if (viewFrame.origin.y != 0) {
viewFrame.origin.y = 0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
}
-(void)keyboardDidShow:(NSNotification*)aNotification{
NSDictionary* info = [aNotification userInfo];
keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
}
-(void)keyboardDidHide:(NSNotification*)aNotification{
[self restoreViewFrameOrigionYToZero];// keyboard is dismissed, restore frame view to its zero origin
}
#end
On swift 4
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(getInfo(notif:)), name: .UIKeyboardDidShow , object: nil)
}
and then:
#objc func getInfo(notif: NSNotification) -> Void {
guard let userInfo = notif.userInfo else {return}
if let myData = userInfo["UIKeyboardFrameBeginUserInfoKey"] as? CGRect {
print(myData.width)
print(myData.height)
}
}

How to get UIKeyboard size with iOS

Is there some way to get UIKeyboard size programmatically. 216.0f height and 162.0f height in landscape.
Following seem to be deprecated. Is there some way that works without any warning in both 3.0 iPhone OS SDK and 4.0 iPhone OS SDK to do this..
CGSize keyBoardSize = [[[note userInfo]
objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
You can get the keyboard size from the userInfo dictionary using the UIKeyboardFrameBeginUserInfoKey and the UIKeyboardFrameEndUserInfoKey instead.
These two keys return a NSValue instance containing a CGRect that holds the position and size of the keyboard at both the start and end points of the keyboard's show/hide animation.
Edit:
To clarify, the userInfo dictionary comes from an NSNotification instance. It's passed to your method that you register with an observer. For example,
- (void)someMethodWhereYouSetUpYourObserver
{
// This could be in an init method.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myNotificationMethod:)
name:UIKeyboardDidShowNotification
object:nil];
}
- (void)myNotificationMethod:(NSNotification*)notification
{
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}
Edit 2:
Also, please don't forget to remove yourself as an observer in your dealloc method! This is to avoid a crash that would occur when the notification center tries to notify your object after its been freed.
You should use the UIKeyboardWillChangeFrameNotification instead, because some international keyboards, like the Chinese keyboard, will change frames during use. Also make sure to convert the CGRect into the proper view, for landscape use.
//some method like viewDidLoad, where you set up your observer.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
- (void)keyboardWillChange:(NSNotification *)notification {
CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; //this is it!
}
Here's how I finally made works. I combined suggestions and codes from different answers.
Features: dismissing keyboard, moving text fields above keyboard while editing and setting "Next" and "Done" keyboard return type.REPLACE "..." with more fields
static const CGFloat ANIMATION_DURATION = 0.4;
static const CGFloat LITTLE_SPACE = 5;
CGFloat animatedDistance;
CGSize keyboardSize;
#interface ViewController () <UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *firstNameTXT;
.....// some other text fields
#property (weak, nonatomic) IBOutlet UITextField *emailTXT;
#end
#implementation ViewController
- (void)viewDidLoad{
.....
// add tap gesture to help in dismissing keyboard
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(tapScreen:)];// outside textfields
[self.view addGestureRecognizer:tapGesture];
// set text fields return key type to Next, last text field to Done
[self.firstNameTXT setReturnKeyType:UIReturnKeyNext];
.....
[self.emailTXT setReturnKeyType:UIReturnKeyDone];
// set text fields tags
[self.firstNameTXT setTag:0];
....// more text fields
[self.emailTXT setTag:5];
// add keyboard notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}
// dismiss keyboard when tap outside text fields
- (IBAction)tapScreen:(UITapGestureRecognizer *)sender {
if([self.firstNameTXT isFirstResponder])[self.firstNameTXT resignFirstResponder];
...
if([self.emailTXT isFirstResponder])[self.emailTXT resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
if(textField.returnKeyType==UIReturnKeyNext) {
// find the text field with next tag
UIView *next = [[textField superview] viewWithTag:textField.tag+1];
[next becomeFirstResponder];
} else if (textField.returnKeyType==UIReturnKeyDone || textField.returnKeyType==UIReturnKeyDefault) {
[textField resignFirstResponder];
}
return YES;
}
// Moving current text field above keyboard
-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField{
CGRect viewFrame = self.view.frame;
CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
CGFloat textFieldBottomLine = textFieldRect.origin.y + textFieldRect.size.height + LITTLE_SPACE;//
CGFloat keyboardHeight = keyboardSize.height;
BOOL isTextFieldHidden = textFieldBottomLine > (viewRect.size.height - keyboardHeight)? TRUE :FALSE;
if (isTextFieldHidden) {
animatedDistance = textFieldBottomLine - (viewRect.size.height - keyboardHeight) ;
viewFrame.origin.y -= animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
return YES;
}
-(void) restoreViewFrameOrigionYToZero{
CGRect viewFrame = self.view.frame;
if (viewFrame.origin.y != 0) {
viewFrame.origin.y = 0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
}
-(void)keyboardDidShow:(NSNotification*)aNotification{
NSDictionary* info = [aNotification userInfo];
keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
}
-(void)keyboardDidHide:(NSNotification*)aNotification{
[self restoreViewFrameOrigionYToZero];// keyboard is dismissed, restore frame view to its zero origin
}
#end
On swift 4
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(getInfo(notif:)), name: .UIKeyboardDidShow , object: nil)
}
and then:
#objc func getInfo(notif: NSNotification) -> Void {
guard let userInfo = notif.userInfo else {return}
if let myData = userInfo["UIKeyboardFrameBeginUserInfoKey"] as? CGRect {
print(myData.width)
print(myData.height)
}
}

Resources