3
votes

I have TWO UITextViews, one at the top of the UIView another at the bottom of UIView.

I use this code, to move UIView when Keyboard appears.

  - (void) viewDidLoad
{

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

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

}


-(void)keyboardWillShow {
    // Animate the current view out of the way
    [UIView animateWithDuration:0.3f animations:^ {
        self.frame = CGRectMake(0, -160, 320, 480);
    }];
}

-(void)keyboardWillHide {
    // Animate the current view back to its original position
    [UIView animateWithDuration:0.3f animations:^ {
        self.frame = CGRectMake(0, 0, 320, 480);
    }];
}

It works great when I use the UITextView from bottom. BUT MY PROBLEM IS, When I want to use the UITextView from Top of the UIView, the keyboard appears, the UIView moves up, but also my top UITextView moves up. Help me please, I don't want to move the UIView if user wants to type text on UITextView from top.

1

1 Answers

7
votes

A really simple way to do this that I use in my projects is the TPKeyboardAvoiding library.

https://github.com/michaeltyson/TPKeyboardAvoiding

Download the source, drop the 4 files into your project. In InterfaceBuilder make sure your TextViews are inside a UIScrollView or UITableView, then change the class of that scroll view or tableview to be the TPAvoiding subclasses.

If you don't want to do that, your other option is to check which TextView is being used and only animate if the keyboard you want is the one selected, i.e.:

-(void)keyboardWillShow {
    // Animate the current view out of the way
   if ([self.textFieldThatNeedsAnimation isFirstResponder]) {
        [UIView animateWithDuration:0.3f animations:^ {
        self.frame = CGRectMake(0, -160, 320, 480);
        }];
        self.animated = YES;
    }
}

-(void)keyboardWillHide {
    // Animate the current view back to its original position
    if (self.animated) {
      [UIView animateWithDuration:0.3f animations:^ {
          self.frame = CGRectMake(0, 0, 320, 480);
      }];
      self.animated = NO;
    }
}