0

I have a simple UITextField, that when someone goes to edit it, and the keyboard pops up, the view shifts up so that the user can see what they are entering. However, when I close the keyboard, the view is not returning to the original position! I am using a CGPoint property to capture its original position on viewDidLoad and then try and set it back to that when the keyboard is closed.

Code:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Set the original center point for shifting the view
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    self.originalCenter = self.view.center;
}

- (void)doneWithNumberPad {

    [locationRadius resignFirstResponder];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25];
    self.view.center = self.originalCenter;
    [UIView commitAnimations];
}

- (void)keyboardDidShow:(NSNotification *)note
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25];
    self.view.center = CGPointMake(self.originalCenter.x, 150);
    [UIView commitAnimations];
}
Jano
  • 62,815
  • 21
  • 164
  • 192
Jon Erickson
  • 1,876
  • 4
  • 30
  • 73

2 Answers2

1

When viewDidLoad is called, your view hierarchy has not yet been laid out for the current device's screen size or orientation. It is too early to look at self.view.center.

Do it in viewDidLayoutSubviews instead.

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.originalCenter = self.view.center;
}

Note that if you support autorotation, even this won't work properly if the keyboard is visible when the autorotation happens.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

If you do not require an absolute final center position, a sure-fire way to get this to work is to shift the views up by a fixed value defined by you when the keyboard shows and shift it down by that fixed value when the keyboard hides.

#define OFFSET 100

- (void)doneWithNumberPad {
    [locationRadius resignFirstResponder];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25];
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + OFFSET);
    [UIView commitAnimations];
}

- (void)keyboardDidShow:(NSNotification *)note
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25];
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y - OFFSET);
    [UIView commitAnimations];
}
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141