Ishwarya Ishwarya - 1 month ago 8
iOS Question

Keyboard move up and down with many subviews with uiTextfield

I need to move a keyboard up and down. I have many subviews with many uiTextfields. These subviews has one superview and this superview is in the scroll view.

I can't move up a view using below code:

- (void) keyboardWasShown:(NSNotification *)notification{
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0);
self.Scroll_view.contentInset = contentInsets;
self.Scroll_view.scrollIndicatorInsets = contentInsets;

- (void) keyboardWillBeHidden:(NSNotification *)notification{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.Scroll_view.contentInset = contentInsets;
self.Scroll_view.scrollIndicatorInsets = contentInsets;

This code working fine when i place all the UITextfields in the ScrollView(Not into the subviews), But i need to do with subview and also move keyboard up and down.
How can i move a keyboard up and down while press keyboard Next/Return key?


Try This:

- (void)animateViewUpToTargetYOrigin:(CGFloat)yValue

    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardDidChangeFrameNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        CGFloat yOrigin = 0;
        CGFloat keyboardYOrigin = [[[note userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
        if (yValue > keyboardYOrigin) {
            yOrigin = yValue - keyboardYOrigin;
        [UIView animateWithDuration:0.3f animations:^{

                self.view.frame = CGRectMake(self.frame.origin.x, -yOrigin, self.frame.size.width, self.frame.size.height);



Using this code you only need to call this method in textfield didbeginediting, and pass the yOrigin(textfield)+height(textField) as y value in it. If you textFields are in Scrollview or any sub view convert their frame values in respect to self.view before sending Y value.


CGRect textFieldRectWithRespectToSelfView = [textField.superview convertRect:textField.frame toView:self.view];
[self.view animateViewUpToTargetYOrigin: textFieldRectWithRespectToSelfView.orgin.y + textFieldRectWithRespectToSelfView.size.height];

When you call [textField resignFirstResponder], self.view comes back to its original position. This happens because the UIKeyboardDidChangeFrameNotification always keeps listening to keyboard frame changes.

I do have a demo project in github as an example please refer to it: