Rectangle 27 16

Your code seems to be correct but i will prefer using UIKeyboardDidChangeFrameNotification or UIKeyboardWillChangeFrameNotification because these will tell you the change in keyboard frame when predictive text bar gets up or down when keyboard is in view.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardFrameDidChange:)
                                             name:UIKeyboardDidChangeFrameNotification object:nil];

and then paste this method in your ViewController

-(void)keyboardFrameDidChange:(NSNotification*)notification{
    NSDictionary* info = [notification userInfo];

    CGRect kKeyBoardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [yourView setFrame:CGRectMake(0, kKeyBoardFrame.origin.y-yourView.frame.size.height, 320, yourView.frame.size.height)];
}

This will handle all your keyboard cases like when its up or down or change in its frame with predictive text bar

and also remove observer when you are leaving your view

@ngb what exactly are you saying?

@pankajwadhwa Nothing happens in my case. I have a view pinned to bottom-space. I tried your above code. I'm getting the values for kKeyBoardFrame. But the [yourView setFrame:...] ain't working. What might be the reason? thanks.

uitableview - iOS 8 UIView not moving up when keyboard appears - Stack...

uitableview uiview keyboard uitextfield ios8
Rectangle 27 16

Your code seems to be correct but i will prefer using UIKeyboardDidChangeFrameNotification or UIKeyboardWillChangeFrameNotification because these will tell you the change in keyboard frame when predictive text bar gets up or down when keyboard is in view.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardFrameDidChange:)
                                             name:UIKeyboardDidChangeFrameNotification object:nil];

and then paste this method in your ViewController

-(void)keyboardFrameDidChange:(NSNotification*)notification{
    NSDictionary* info = [notification userInfo];

    CGRect kKeyBoardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [yourView setFrame:CGRectMake(0, kKeyBoardFrame.origin.y-yourView.frame.size.height, 320, yourView.frame.size.height)];
}

This will handle all your keyboard cases like when its up or down or change in its frame with predictive text bar

and also remove observer when you are leaving your view

@ngb what exactly are you saying?

@pankajwadhwa Nothing happens in my case. I have a view pinned to bottom-space. I tried your above code. I'm getting the values for kKeyBoardFrame. But the [yourView setFrame:...] ain't working. What might be the reason? thanks.

uitableview - iOS 8 UIView not moving up when keyboard appears - Stack...

uitableview uiview keyboard uitextfield ios8
Rectangle 27 1

I just ran into this and made a discovery I thought I would share. In iOS 8 layout passes for the sub views of the main view will be done whenever the keyboard is about to appear or about to go away. These passes do not get done on iOS 7. So if you try to animate a sub view of the main view in keyBoardWillShow or keyboardWillChangeFrame the animation will get undone by the layout pass and your sub views that you tried to animate will move back to their original position. That is why keyboardDidChangeFrame works to animate the subviews and keyboardWillChangeFrame does not.

Something odd I noted as well is the timing of when these calls are made. It seems the first time that the keyboard appears after the app is launched, the call to keyboardDidChangeFrame happens too late to be able to animate with the keyboard so they slide up together, but on second and subsequent times the keyboard shows, the call to keyboardDidChangeFrame happens sooner and it seems you can actually animate the views along with the keyboard.

I must note that I am using C# and Xamarin as my development platform for iOS, so this may be different when using Swift or Obj-C.

uitableview - iOS 8 UIView not moving up when keyboard appears - Stack...

uitableview uiview keyboard uitextfield ios8
Rectangle 27 1

I just ran into this and made a discovery I thought I would share. In iOS 8 layout passes for the sub views of the main view will be done whenever the keyboard is about to appear or about to go away. These passes do not get done on iOS 7. So if you try to animate a sub view of the main view in keyBoardWillShow or keyboardWillChangeFrame the animation will get undone by the layout pass and your sub views that you tried to animate will move back to their original position. That is why keyboardDidChangeFrame works to animate the subviews and keyboardWillChangeFrame does not.

Something odd I noted as well is the timing of when these calls are made. It seems the first time that the keyboard appears after the app is launched, the call to keyboardDidChangeFrame happens too late to be able to animate with the keyboard so they slide up together, but on second and subsequent times the keyboard shows, the call to keyboardDidChangeFrame happens sooner and it seems you can actually animate the views along with the keyboard.

I must note that I am using C# and Xamarin as my development platform for iOS, so this may be different when using Swift or Obj-C.

uitableview - iOS 8 UIView not moving up when keyboard appears - Stack...

uitableview uiview keyboard uitextfield ios8
Rectangle 27 2

The accepted Answer is almost right. To match your view's animation to that of the keyboard you want to use the UIKeyboardWillChangeFrameNotification rather than the UIKeyboardDidChangeFrameNotification. That way the animations you kick off will precisely match that of the keyboard. Here's some code to do the entire thing. I use the animation of the keyboard to drive the animation of my autolayout constraint constants, but you can easily adapt this to animate an entire view frame. (Note, we have to use the old school style animations to hook into the UIKeyboardCurveInfoKey which provides an animation curve exactly matching the keyboard animation.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardFrameDidChange:)
                                             name:UIKeyboardWillChangeFrameNotification
                                           object:nil];
- (void)keyboardFrameDidChange:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];

    CGRect kKeyBoardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = kKeyBoardFrame.size.height; 
    [self.view removeConstraints:self.verticalButtonConstraints];
    NSDictionary *metrics = @{@"height" : @(height)};
    NSDictionary *views = @{@"nextButton" : self.nextButton};

    self.verticalButtonConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:  [nextButton(52)]-(height)-|" options:0 metrics:metrics views:views];
    [self.view addConstraints:self.verticalButtonConstraints];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [self.view layoutIfNeeded];
   [UIView commitAnimations];

uitableview - iOS 8 UIView not moving up when keyboard appears - Stack...

uitableview uiview keyboard uitextfield ios8
Rectangle 27 2

The accepted Answer is almost right. To match your view's animation to that of the keyboard you want to use the UIKeyboardWillChangeFrameNotification rather than the UIKeyboardDidChangeFrameNotification. That way the animations you kick off will precisely match that of the keyboard. Here's some code to do the entire thing. I use the animation of the keyboard to drive the animation of my autolayout constraint constants, but you can easily adapt this to animate an entire view frame. (Note, we have to use the old school style animations to hook into the UIKeyboardCurveInfoKey which provides an animation curve exactly matching the keyboard animation.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardFrameDidChange:)
                                             name:UIKeyboardWillChangeFrameNotification
                                           object:nil];
- (void)keyboardFrameDidChange:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];

    CGRect kKeyBoardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = kKeyBoardFrame.size.height; 
    [self.view removeConstraints:self.verticalButtonConstraints];
    NSDictionary *metrics = @{@"height" : @(height)};
    NSDictionary *views = @{@"nextButton" : self.nextButton};

    self.verticalButtonConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:  [nextButton(52)]-(height)-|" options:0 metrics:metrics views:views];
    [self.view addConstraints:self.verticalButtonConstraints];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [self.view layoutIfNeeded];
   [UIView commitAnimations];

uitableview - iOS 8 UIView not moving up when keyboard appears - Stack...

uitableview uiview keyboard uitextfield ios8
Rectangle 27 92

I've put together a universal, drop-in UIScrollView, UITableView and even UICollectionView subclass that takes care of moving all text fields within it out of the way of the keyboard.

When the keyboard is about to appear, the subclass will find the subview that's about to be edited, and adjust its frame and content offset to make sure that view is visible, with an animation to match the keyboard pop-up. When the keyboard disappears, it restores its prior size.

It should work with basically any setup, either a UITableView-based interface, or one consisting of views placed manually.

This is it! This is the best, most efficient, and perfect solution! It also handles rotations properly for scroll views. If rotating be sure to autoresize vertically but do not anchor at the bottom. I added a UITextView to the scroll view in my case. Thanks bunches!

Very nice work! Sure, I'm being lazy using your solution instead of the DIY one, but my boss is happier, so yeah! Even if someone does want to do themselves, I like your subclass approach, instead of adding code to each controller. I was shocked iOS didn't do this by default like Android did -- then again, I'm finding a lot of things lacking in iOS and MacOS :(

I spent the whole day yesterday trying to get one of the other answers to work (trying to avoid adding a whole library). Today I plug this in, except for minimal work, it works fine. By minimal work I mean renaming my scrollviews as TPKeyboardAvoidingScrollView

Does weird things like my scrollview all fits in the screen, so it can't be scrolled. After opening and closing the keyboard, the content is now larger (looks like something invisible was added and not removed at the bottom of the page), and can be scrolled.

ios - How to make a UITextField move up when keyboard is present? - St...

ios objective-c uitextfield uikeyboard
Rectangle 27 40

This document details a solution to this problem. Look at the source code under 'Moving Content That Is Located Under the Keyboard'. It's pretty straightforward.

EDIT: Noticed there's a wee glitch in the example. You will probably want to listen for UIKeyboardWillHideNotification instead of UIKeyboardDidHideNotification. Otherwise the scroll view behind of the keyboard will be clipped for the duration of the keyboard closing animation.

ios - How to make a UITextField move up when keyboard is present? - St...

ios objective-c uitextfield uikeyboard
Rectangle 27 910

#define kOFFSET_FOR_KEYBOARD 80.0

-(void)keyboardWillShow {
    // Animate the current view out of the way
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)keyboardWillHide {
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if ([sender isEqual:mailTf])
    {
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
    }
}

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view

    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;

    [UIView commitAnimations];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // register for keyboard notifications
    [[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
{
    [super viewWillDisappear:animated];
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                             name:UIKeyboardWillHideNotification
                                           object:nil];
}

It's the field that you use to say "when the user is editing here the view should slide up" or something so... However you can remove that if, if you more fields.

isn't it batter to call -(void)setViewMovedUp:(BOOL)movedUp in keyBoardWillSHow and KeyBoardWillHide events!!

Is the benefit of this example over the next that it does not require a UIScrollView? I don't want to have to put the contents of the view in an otherwise useless UIScrollView if its not necessary.

Not particularly useful if you're supporting rotations of the main view.

ios - How to make a UITextField move up when keyboard is present? - St...

ios objective-c uitextfield uikeyboard
Rectangle 27 63

Make sure that if you are overriding viewWillAppear that you call [super viewWillAppear:animated]; If you don't, the Scroll View will not scroll up properly. Swift super.viewWillAppear(animated) share|improve this answer edited Aug 23 at 21:07 al_mota 327 answered Jun 28 '12 at 11:42 LJ Wilson 13.2k42852

You know what...You are God for me !

That's a good example why you should always call super, especially if this explicitly specified in the documentation ))

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

ios - UITableViewController not scrolling view when keyboard appears -...

ios cocoa-touch
Rectangle 27 14

It doesn't require a scroll view to be able to move the view frame. You can change the frame of a viewcontroller's view so that the entire view moves up just enough to put the firstresponder text field above the keyboard. When I ran into this problem I created a subclass of UIViewController that does this. It observes for the keyboard will appear notification and finds the first responder subview and (if needed) it animates the main view upward just enough so that the first responder is above the keyboard. When the keyboard hides, it animates the view back where it was.

To use this subclass make your custom view controller a subclass of GMKeyboardVC and it inherits this feature (just be sure if you implement viewWillAppear and viewWillDisappear they must call super). The class is on github.

What license? Some of your files there have an open source license and some don't.

Warning: this code is not friendly with ARC projects.

You just add the build option to specify that those are non-ARC files or welcome to convert it to ARC and submit a pull request.

ios - How to make a UITextField move up when keyboard is present? - St...

ios objective-c uitextfield uikeyboard
Rectangle 27 9

I see all answers are moving the view itself by the value of the keyboard height. Well, I have an elaborate answer, which could be useful if you are using constraints i.e autolayout, that moves a view by changing its constraint value (bottom or top constraints for example) by a predefined value or you can use keyboard size value.

In this example, I use bottom constraint from the textfield to Bottom Layout View with initial value of 175.

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

override func 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);
}

func keyboardWillShow(notification: NSNotification) {
    //To retrieve keyboard size, uncomment following line
    //let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
    bottomConstraint.constant = 260
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

func keyboardWillHide(notification: NSNotification) {
    //To retrieve keyboard size, uncomment following line
    //let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
    bottomConstraint.constant = 175
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

You are correct sir

ios - Move view with keyboard using Swift - Stack Overflow

ios swift uikit nsnotificationcenter uikeyboard
Rectangle 27 17

-(void)textFieldDidEndEditing:(UITextField *)sender

{
    //move the main view, so that the keyboard does not hide it.
    if  (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

ios - How to make a UITextField move up when keyboard is present? - St...

ios objective-c uitextfield uikeyboard
Rectangle 27 23

RPDP's code successfully moves the text field out of the way of the keyboard. But when you scroll to the top after using and dismissing the keyboard, the top has been scrolled up out of the view. This is true for the Simulator and the device. To read the content at the top of that view, one has to reload the view.

Isn't his following code supposed to bring the view back down?

else
{
    // revert back to the normal state.
    rect.origin.y += kOFFSET_FOR_KEYBOARD;
    rect.size.height -= kOFFSET_FOR_KEYBOARD;
}

ios - How to make a UITextField move up when keyboard is present? - St...

ios objective-c uitextfield uikeyboard
Rectangle 27 2

You have to subscribe for UIKeyboardWillShowNotification and UIKeyboardWillHideNotification. Then move modal view up when keyboard appears, down when keyboard hides.

[UIView animateWithDuration:ANIMATION_DURATION animations:^{
    CGRect currentFrame = modalView.frame;
    currentFrame.origin.y += VIEW_FRAME_OFFSET;
    modalView.frame = currentFrame;
}];

Also if you want you can use other keyboard notifications listed here.

The Uiview only moves quickly after implement this code and returns to the same point, beneath the keyboard. Any ideia? Thanks!

ios - How to move up a modal UIView inside of a UIViewcontroller (Stor...

ios iphone uiview uiviewcontroller keyboard
Rectangle 27 139

Your problem is well explained in this document by Apple. Example code in this page (at Listing 4-1) do exactly what you need: will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew. The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:

Declare a variable

var activeField: UITextField?
func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.scrollEnabled = true
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeFieldPresent = activeField
    {
        if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }


}


func keyboardWillBeHidden(notification: NSNotification)
{
    //Once keyboard disappears, restore original positions
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.scrollEnabled = false

}

func textFieldDidBeginEditing(textField: UITextField!)
{
    activeField = textField
}

func textFieldDidEndEditing(textField: UITextField!)
{
    activeField = nil
}

Be sure to declare your ViewController as UITextFieldDelegate and set correct delegates in your initialization methods: ex:

self.you_text_field.delegate = self
registerForKeyboardNotifications
deregisterFromKeyboardNotifications
func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}

Nerkyator could you elaborate a little more on registerForKeyboardNotifications? Where, when and why would I call this method? Thanks

You have to call registerForKeyboardNotifications at viewDidLoad, so you will add an observer to notification center for when keyboard appears or disappears from screen. When these notification fire, methods keyboardWasShown and keyboardWillBeHidden will be called and then scrollview will move accordingly to keyboard size. You can find more detailed information about NotificationCenter here: developer.apple.com/library/mac/documentation/Cocoa/Reference/

private func findActiveTextField (subviews : [UIView], inout textField  : UITextField?) {                  for view in subviews {             if let tf = view as? UITextField where view.isFirstResponder() {                 textField = tf                 break             }             else if !view.subviews.isEmpty {                 findActiveTextField (view.subviews, textField: &textField)             }         }    }

Thanks, that's exactly what I was looking for - an apple recommended solution. However, in my case I already had a scroll view that spanned outside the viewable area. This code would disable scrolling after the keyboard would hide. I removed "self.scrollView.scrollEnabled = false" and it would still not scroll. What worked for me was "self.scrollView.contentInset = UIEdgeInsetsZero;" this single line in keyboardWillHide event

ios - Move a view up only when the keyboard covers an input field - St...

ios swift keyboard xcode6
Rectangle 27 139

Your problem is well explained in this document by Apple. Example code in this page (at Listing 4-1) do exactly what you need: will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew. The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:

Declare a variable

var activeField: UITextField?
func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.scrollEnabled = true
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeFieldPresent = activeField
    {
        if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }


}


func keyboardWillBeHidden(notification: NSNotification)
{
    //Once keyboard disappears, restore original positions
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.scrollEnabled = false

}

func textFieldDidBeginEditing(textField: UITextField!)
{
    activeField = textField
}

func textFieldDidEndEditing(textField: UITextField!)
{
    activeField = nil
}

Be sure to declare your ViewController as UITextFieldDelegate and set correct delegates in your initialization methods: ex:

self.you_text_field.delegate = self
registerForKeyboardNotifications
deregisterFromKeyboardNotifications
func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}

Nerkyator could you elaborate a little more on registerForKeyboardNotifications? Where, when and why would I call this method? Thanks

You have to call registerForKeyboardNotifications at viewDidLoad, so you will add an observer to notification center for when keyboard appears or disappears from screen. When these notification fire, methods keyboardWasShown and keyboardWillBeHidden will be called and then scrollview will move accordingly to keyboard size. You can find more detailed information about NotificationCenter here: developer.apple.com/library/mac/documentation/Cocoa/Reference/

private func findActiveTextField (subviews : [UIView], inout textField  : UITextField?) {                  for view in subviews {             if let tf = view as? UITextField where view.isFirstResponder() {                 textField = tf                 break             }             else if !view.subviews.isEmpty {                 findActiveTextField (view.subviews, textField: &textField)             }         }    }

Thanks, that's exactly what I was looking for - an apple recommended solution. However, in my case I already had a scroll view that spanned outside the viewable area. This code would disable scrolling after the keyboard would hide. I removed "self.scrollView.scrollEnabled = false" and it would still not scroll. What worked for me was "self.scrollView.contentInset = UIEdgeInsetsZero;" this single line in keyboardWillHide event

ios - Move a view up only when the keyboard covers an input field - St...

ios swift keyboard xcode6
Rectangle 27 9

You need to adjust the height of your scroll view when the keyboard appears so that it doesn't overlap. See Managing the Keyboard in the programming guide.

See section "Moving Content That Is Located Under the Keyboard". It has source code with it as well

ios - iPhone: keyboard blocks screen - Stack Overflow

iphone ios interface-builder
Rectangle 27 2

We'll, I'm pretty stoked now. I've figured this out. This can be solved using the new, iOS8 UIPresentationController. I'll give some sample code below. And try to link in a working project zip file later.

The first view controller is the root view controller of the example app. Code for the ChangeFrameTransitioningDelegate follows below. "Dialog" is just an empty view controller class.

//
//  ViewController.m
//  TestPresentationController
//
//  Created by Christopher Prince on 9/21/14.
//  Copyright (c) 2014 Spastic Muffin, LLC. Use at your own discretion.
//

#import "ViewController.h"
#import "ChangeFrameTransitioningDelegate.h"
#import "Dialog.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void) viewDidAppear:(BOOL)animated;
{
    [super viewDidAppear:animated];

    ChangeFrameTransitioningDelegate *td = [ChangeFrameTransitioningDelegate new];
    td.viewControllerFrame = CGRectMake(100, 0, 100, 100);

    Dialog *d = [Dialog new];
    // Just to make the VC stand out.
    d.view.backgroundColor = [UIColor greenColor];

    // Need to make this custom in order to have the presentationControllerForPresentedViewController method of the transitioning delegate called.
    d.modalPresentationStyle = UIModalPresentationCustom;

    d.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    d.transitioningDelegate = td;

    [self presentViewController:d animated:YES completion:^{

        // Any time after the view controller is presented you can change the
        // viewControllerFrame property to change the size and/or position of the 
        // presented view controller.
        [UIView animateWithDuration:0.5 animations:^{
            td.viewControllerFrame = CGRectMake(100, 800, 100, 100);
        }];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
//
//  ChangeFrameTransitioningDelegate.m
//  TestPresentationController
//
//  Created by Christopher Prince on 9/21/14.
//  Copyright (c) 2014 Spastic Muffin, LLC. Use at your own discretion.
//

// Some help from http://stackoverflow.com/questions/25903412/editing-bounds-of-uiview-when-presenting-hides-keyboard-in-ios-8
// http://stackoverflow.com/questions/25811199/ios-8-change-the-size-of-presented-modal-view-controller
// Some code from https://developer.apple.com/devcenter/download.action?path=/wwdc_2014/wwdc_2014_sample_code/lookinsidepresentationcontrollersadaptivityandcustomanimatorobjects.zip (though, beware, this example doesn't work straight out of the box).
// And see http://stackoverflow.com/questions/25957343/moving-a-modally-presented-uiviewcontroller-up-when-keyboard-appears-on-ipad-wit

#ifndef SPASLogDetail
#define SPASLogDetail NSLog
#endif

#import "ChangeFrameTransitioningDelegate.h"

@interface PresentationController : UIPresentationController
{
    UIView *_dimmingView;
}
// This is the size and position that the PresentationController will use when its frameOfPresentedViewInContainerView method is called.
@property (nonatomic) CGRect currentFrame;
@end

@implementation PresentationController

- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController;
{
    self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController];
    // Some random default size.
    self.currentFrame = CGRectMake(0, 0, 100, 100);
    [self prepareDimmingView];
    return self;
}

// 4/22/15; Added, for rotation.
- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator;
{
    CGSize increasedSize = size;
    // 4/22/15; I'm getting some odd effects: In a rotation transition from landscape to portrait, the RHS goes white momentarily, and from portrait to landscape, the bottom goes white momentarily. A hack, but increase the size of the dimming view to get around this.
    increasedSize.width *= 1.5;
    increasedSize.height *= 1.5;
    _dimmingView.frameSize = increasedSize;

    // There appears to be no transitionCoordinator available for this "transition". Therefore using the regular UIView animation, below.
    /*
    if([self.presentedViewController transitionCoordinator])
    {
        [[self.presentedViewController transitionCoordinator] animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            recenterViewController();
        } completion:nil];
    }
    else
    {
        recenterViewController();
    }*/

    // 4/23/15; See [1]. Given that I've turned off resizing with the autoresizingMask, this has messed up the repositioning of the (x, y) coordinate of the presentedViewController. Make up for that here.
    [UIView animateWithDuration: coordinator.transitionDuration animations:^{
        // I'm assuming the size here refers to the entire window.
        CGPoint center = CGPointMake(size.width/2.0, size.height/2.0);
        self.presentedViewController.view.center = center;
    } completion:nil];
}

- (void)presentationTransitionWillBegin
{
    UIView* containerView = [self containerView];

    // 4/23/15; So, this seems to be related to my modal view resizing problem. When I disable autoresizesSubviews, I stop the resizing during the rotation. HOWEVER, this is at the price of two additional problems: (a) the (x, y) coordinate of the modal stops being changed during the rotation, and (b) the animation of the background (_dimmingView?) starts looking funky during the rotation. WHICH makes sense. The containerView size is the full window.
    //containerView.autoresizesSubviews = NO;

    UIViewController* presentedViewController = [self presentedViewController];

    // [1] 4/23/15; This is better. The _dimmingView animation is preserved. The (x, y) position of the presentedViewController, however isn't right after the rotation.
    presentedViewController.view.autoresizingMask = UIViewAutoresizingNone;

    [_dimmingView setFrame:[containerView bounds]];
    [_dimmingView setAlpha:0.0];

    [containerView insertSubview:_dimmingView atIndex:0];

    void (^setAlpha)() = ^{
        [_dimmingView setAlpha:1.0];
    };

    if([presentedViewController transitionCoordinator])
    {
        [[presentedViewController transitionCoordinator] animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            setAlpha();
        } completion:nil];
    }
    else
    {
        setAlpha();
    }
}

- (void)dismissalTransitionWillBegin
{
    void (^resetAlpha)() = ^{
        [_dimmingView setAlpha:0.0];
    };

    if([[self presentedViewController] transitionCoordinator])
    {
        [[[self presentedViewController] transitionCoordinator] animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            resetAlpha();
        } completion:nil];
    }
    else
    {
        resetAlpha();
    }
}

- (CGRect)frameOfPresentedViewInContainerView
{
    SPASLogDetail(@"frameOfPresentedViewInContainerView: %@", NSStringFromCGRect(self.currentFrame));
    return self.currentFrame;
}

- (void) setCurrentFrame:(CGRect)currentFrame
{
    _currentFrame = currentFrame;
    // This is the important part for changing the frame of the presented view controller *after* the view is presented. For some odd reason, its not right to change the frame of the containerView.
    self.presentedView.frame = currentFrame;
}

- (void) containerViewWillLayoutSubviews;
{
    SPASLogDetail(@"containerViewWillLayoutSubviews");
}

- (void)prepareDimmingView
{
    _dimmingView = [[UIView alloc] init];
    [_dimmingView setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.4]];
    [_dimmingView setAlpha:0.0];

    //UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dimmingViewTapped:)];
    //[_dimmingView addGestureRecognizer:tap];
}

/*
- (void)dimmingViewTapped:(UIGestureRecognizer *)gesture
{
    if([gesture state] == UIGestureRecognizerStateRecognized)
    {
        [[self presentingViewController] dismissViewControllerAnimated:YES completion:NULL];
    }
}*/

@end

@interface ChangeFrameTransitioningDelegate()
@property (nonatomic, strong) PresentationController *presentationController;
@end

@implementation ChangeFrameTransitioningDelegate

- (instancetype) init;
{
    self = [super init];
    return self;
}

- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    self.presentationController = [[PresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    self.presentationController.currentFrame = self.viewControllerFrame;

    return self.presentationController;
}

- (void) setViewControllerFrame:(CGRect)viewControllerFrame
{
    _viewControllerFrame = viewControllerFrame;
    self.presentationController.currentFrame = viewControllerFrame;
}

@end

Hmmmm. I'm now seeing a problem with this. It comes with rotating the device. The modal dialog dimensions are not preserved when the modal is displayed and you rotate the device.

I've just added some changes. See my recently dated comments in the code. I think I've fixed it.

Moving a modally presented UIViewController up when keyboard appears o...

ipad uiviewcontroller uinavigationcontroller ios8