14

For my keyboards to move up to uncover UITextField in my iOS app, I used to implement this answer: https://stackoverflow.com/a/6908258/3855618 on iOS7 and 8 and it has worked perfectly for now. However on iOS 9.1, it doesn't work anymore.

To be more accurate, even if the background view does move up, the UITextField doesn't.

Any idea of what has changed so much since iOS9 and iOS 9.1?

4
  • I have the same problem... did you find a solution for it?
    – Blue
    Sep 22, 2015 at 9:58
  • Unfortunately @Blue I'm still looking for a solution
    – Gannicus
    Sep 22, 2015 at 10:10
  • Ok, I started a bounty... let's see who will get it... ;)
    – Blue
    Sep 22, 2015 at 11:32
  • have you tried what I suggest ? all you have to do is add scroll view with height and width equal to device height and width and copy paste all UI element on scrollView and place them in right position and use suggested constraints. Sep 29, 2015 at 5:39

7 Answers 7

36
+100

The answer you have linked is not recommended. You should not set the view controller view's frame directly, especially not if you are using auto layout. Instead of changing the view's frame you should add a scrollview as a subview to the view, and adjust the content inset when the keyboard is shown or hidden.

From the official apple doc:

When asked to display the keyboard, the system slides it in from the bottom of the screen and positions it over your app’s content. Because it is placed on top of your content, it is possible for the keyboard to be placed on top of the text object that the user wanted to edit. When this happens, you must adjust your content so that the target object remains visible.

Adjusting your content typically involves temporarily resizing one or more views and positioning them so that the text object remains visible. The simplest way to manage text objects with the keyboard is to embed them inside a UIScrollView object (or one of its subclasses like UITableView). When the keyboard is displayed, all you have to do is reset the content area of the scroll view and scroll the desired text object into position. Thus, in response to a UIKeyboardDidShowNotification, your handler method would do the following:

  1. Get the size of the keyboard.
  2. Adjust the bottom content inset of your scroll view by the keyboard height.
  3. Scroll the target text field into view.
 // Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
   NSDictionary* info = [aNotification userInfo];
   CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

   UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
   scrollView.contentInset = contentInsets;
   scrollView.scrollIndicatorInsets = contentInsets;

   // If active text field is hidden by keyboard, scroll it so it's visible
   // Your app might not need or want this behavior.
   CGRect aRect = self.view.frame;
   aRect.size.height -= kbSize.height;
   if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
     [self.scrollView scrollRectToVisible:activeField.frame animated:YES];
   }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
   UIEdgeInsets contentInsets = UIEdgeInsetsZero;
   scrollView.contentInset = contentInsets;
   scrollView.scrollIndicatorInsets = contentInsets;
}
6
  • Ok, I'm trying to use your code, I addedd a scrollview, I putted the textField on the scrollview, I declared the scrollView and synthesized, I also added subscribe and unsuscribe keyboardNotifications observers and when the keyboard appears a NSLog inside your "keyboardWasShown" void is called... but still the textfield doesn't move.. what should I do more?
    – Blue
    Sep 26, 2015 at 14:02
  • Are you using auto layout? Does the keyboard actually covers the textfield? It will only scroll up, if the keyboard hides the textfield, otherwise it just sets the content inset, so you can't scroll behind the keyboard
    – Istvan
    Sep 26, 2015 at 15:02
  • I don't use auto layout... The keyboard covers completly the textfield
    – Blue
    Sep 26, 2015 at 18:07
  • Please post some code how do you set up the scroll view and the textfield then
    – Istvan
    Sep 26, 2015 at 18:37
  • 1
    Hi, I couldn't use your code... but I will give you the bounty as I believe that other persons will be helped by your code.
    – Blue
    Sep 29, 2015 at 8:56
8

Zero lines of Code

Devoid of hacks, kludges, workaround and listeners.

The present question has been asked over and over since the dawn of iOS time. No answer on StackOverflow survived more than 2 iOS iterations. Rightly so, because the UIKit keeps changing from underneath your feet. There exists a design as opposed to implementation solution to this ancient problem. Use a UITableViewController.

Use a UITableViewController

When a UITableView is managed by a UITableViewController, the scrolling is managed automatically for you. Never tinker with UIKeyboardWillShowNotification, ever again. Merely create static or dynamic UITableViewCells to layout your interface, add UITextView or UITextField as needed ; merely becoming first responder will scroll the the proper location.

@availability(iOS, introduced=2.0)

UITableViewController

Notes

  1. Works on all iOS since 2.0.
  2. Quote: «Waste no time optimizing a poor algorithm ; pick a better one»
  3. See https://stackoverflow.com/a/32390936/218152.
2
  • I think you are right, and I see this behaving correctly most of the time. But sometimes it's not reliable and the keyboard covers the field anyway (as far as I can tell). I'm trying to figure out why. Apr 4, 2016 at 22:55
  • Even the OS cannot figure out why! If you look carefully, you will see that Apple does it in 2 steps: 1 bring keyboard up 2 figure out where in heaven the final keyboard footprint landed, and scroll the UITableView. Apr 11, 2016 at 1:18
3

We need to take keyboard frame from notification. When get reference of scrollView, tableView, etc. Convert low border of view to window`s coordinates. When determine how much keyboard covers our view, and if difference is greater than 0, we can add inset below. Try this code:

- (void)subscribeKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)unsubscribeKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}


- (void)keyboardWillShow:(NSNotification *)aNotification
{
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];

    UIScrollView *someScrollView = ......

    CGPoint tableViewBottomPoint = CGPointMake(0, CGRectGetMaxY([someScrollView bounds]));
    CGPoint convertedTableViewBottomPoint = [someScrollView convertPoint:tableViewBottomPoint
                                                                           toView:keyWindow];

    CGFloat keyboardOverlappedSpaceHeight = convertedTableViewBottomPoint.y - keyBoardFrame.origin.y;

    if (keyboardOverlappedSpaceHeight > 0)
    {
        UIEdgeInsets tableViewInsets = UIEdgeInsetsMake(0, 0, keyboardOverlappedSpaceHeight, 0);
        [someScrollView setContentInset:tableViewInsets];
    }
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    UIEdgeInsets tableViewInsets = UIEdgeInsetsZero;
    UIScrollView *someScrollView = ......

    [someScrollView setContentInset:tableViewInsets];
}
2
  • mmmmm you got me a little confused... should I use a scrollview? What should I put in UIScrollView *someScrollView = ...... ?
    – Blue
    Sep 24, 2015 at 17:51
  • You must put into scrollView all your scrollable content, so if you add inset to scroll view - you will add automatically inset to all your content Sep 25, 2015 at 7:37
1

Add all UITextField on UIScrollView and use TPKeyboardAvoiding

1

I'm usually listening to keyboard notifications and make according changes to layout constraints. See my other answer for more details and a sample project.

2
  • Sorry, but I don't use Storyboard and constraints.
    – Blue
    Sep 24, 2015 at 13:14
  • @Blue I see. Avoiding Autolayout and Storyboards in iOS9 seems odd to me though :)
    – NKorotkov
    Sep 24, 2015 at 20:56
1

Try this code that I have used in my previous projects:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self didBeginEditingIn:textField];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self didEndEditing];
}


static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216+100;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162+100;

- (void)didBeginEditingIn:(UIView *)view
{
    CGRect textFieldRect = [self.view.window convertRect:view.bounds fromView:view];
    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 ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        _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)didEndEditing
{
    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];
}
1
  • You still have to use constants for the keyboard size. Is there a way to get the actual size from a notification?
    – Sheamus
    Sep 28, 2015 at 20:46
1

i followed the doc from @Istvan to the apple site, and there are a lot of stuff missing to make it work:
1. Set your .h document to <UITextFieldDelegate> (to be able to work with "activefield")
2. In the viewDidLoad, set the delegates to your UITextfields, and set the height of your scrollview content with a bigger height (in my case i've setted 500 more):

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height + 500;
_scrollView.contentSize = CGSizeMake(screenWidth, screenHeight);

And now it's all working...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.