3

I'm new to iOS programming, and I'm having trouble with getting a UIScrollView to move when editing a UITextField that is obscured by the keyboard. The code is straight out of Apple's documentation but it's not working for some reason.

Through debugging I've found that the notifications seem to be getting passed correctly (i.e. it logs "View should resize", but only when activeField is the textField that is under the keyboard) and scrollpoint is being set correctly, but the scrollview still does not move. Also, I'm reasonably sure that the delegation pattern is correct (ViewController is delegate of textFields as well as scrollView)

- (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 application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
    CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
    [scrollView setContentOffset:scrollPoint animated:YES];
    NSLog(@"%@",@"view should resize");
}
}

Seeing as the code is straight from the documentation, I'm probably just missing something simple. Can anyone point me in the direction of things to check for?

Rembrandt Q. Einstein
  • 1,101
  • 10
  • 23

1 Answers1

1

Apple's example has a bug in that it doesn't explicitly set the scroll view's content size and thus uses the default content size which is (0, 0). I fixed this problem by adding this code in my view controller:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set the scroll view's content size to be the same width as the
    // application's frame but set its height to be the height of the
    // application frame minus the height of the navigation bar's frame
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    CGRect navigationFrame = [[self.navigationController navigationBar] frame];
    CGFloat height = applicationFrame.size.height - navigationFrame.size.height;
    CGSize newContentSize = CGSizeMake(applicationFrame.size.width, height);

    ((UIScrollView *)self.view).contentSize = newContentSize;
}
HairOfTheDog
  • 2,489
  • 2
  • 29
  • 35