Siddharth
Siddharth

Reputation: 5219

TextField hidden by keyboard in iOS

I have a textfield which brings up the keyboard. The keyboard hides the bottom of the text field. I have placed my textField inside a scroll view and I have written the following code in the view.

- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification *)aNotification {
    // Called when the keyboard is shown
    NSDictionary *info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    _driverSignupScrollView.contentInset = contentInsets;
    _driverSignupScrollView.scrollIndicatorInsets = contentInsets;

    // If active field is hidden by keyboard, scroll it so it's visible
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;

    CGPoint activeFieldPoint = CGPointMake(_activeField.frame.origin.x, _activeField.frame.origin.y + _activeField.frame.size.height);
    if (!CGRectContainsPoint(aRect, activeFieldPoint)) {
        [_scrollView scrollRectToVisible:_activeField.frame animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification *)aNotification {
    // Called when the keyboard is hidden
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

But the control never goes inside my if (!CGRectContainsPoint(aRect, activeFieldPoint)) and so it does not scroll up.

The _activeField is being set correctly in another method.

Is there anything I am missing here?

Upvotes: 1

Views: 364

Answers (2)

Oren
Oren

Reputation: 5103

Take a look at TPKeyboardAvoiding: https://github.com/michaeltyson/TPKeyboardAvoiding

It makes keyboard management insanely easy. It's how Apple should have designed it to begin with.

Upvotes: 1

Balram Tiwari
Balram Tiwari

Reputation: 5667

You can instead put your textField in UIView & try moving up your UIView.

Here is a sample working code

Upvotes: 0

Related Questions