Lumbrjck
Lumbrjck

Reputation: 35

How to move UITextField after keyboard appears?

I'm working on a little project. It is basically just a text field where you can type in some short text (basically only a few words) and then you have 3 main buttons below (it looks like a tab bar) you have the option to press keyboard to change the text or type in one if you don't have, you can press colors to choose from different colors for your text or you can press the third button where you can change the font.

So, I just started and I have this issue that if I press the keyboard button the keyboard should appear and the textview should automatically move up for 216px (the height of the keyboard) I have the code below:

The 111 in frame.origin are the y-coordiantes where it should move.

- (IBAction)keyBoardAction:(id)sender {

CGRect frame = _textField.frame;
frame.origin.y = 111;

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
_textField.frame = frame;
[UIView commitAnimations];

[_textField becomeFirstResponder];

}

Because it didn't work I run the app without making the textField the firstResponder so that the keyboard would not block my view and I could watch the textField through the whole process.

When I then run the app and pressed the keyboard button, the textField first went down below the screen and then moved upwards again to the same position it was at the beginning.

Upvotes: 0

Views: 117

Answers (1)

Pablo A.
Pablo A.

Reputation: 2052

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

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}


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

    NSTimeInterval duration = userInfo ? [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue] : 1.0;

    CGRect keyboardEndFrame;
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];

    CGRect newFrame = _textField.frame;
    newFrame.origin.y -= keyboardEndFrame.size.height;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: duration];
    _textField.frame = newFrame;
    [UIView commitAnimations];

}

Upvotes: 1

Related Questions