uikeyboardwillhidenotification calling method twice when scroll

869 Views Asked by At

I've a view with UIScrollView and has many UITextField I'm closing the keyboard once I touch the view and it is working fine at the same time I want to close the keyboard when I scroll the view. My issue is when I scroll the view it is closing the keyboard but it is calling the method (keyboardWillHide) two times which make an issue for me setting the screen wrong. How can I prevent from calling the method two times?

My code:

- (void)viewDidLoad {
   [super viewDidLoad];

  UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeTextInput)];
tapGesture.cancelsTouchesInView = NO;
  [self.view addGestureRecognizer:tapGesture];

  _scrllView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];

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

- (void)viewWillDisappear:(BOOL)animated
{
  [super viewWillDisappear:animated];

  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillShowNotification
                                              object:nil];

  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillHideNotification
                                              object:nil];
}

-(void)keyboardWillHide {

    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)setViewMovedUp:(BOOL)movedUp{

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    CGRect rect = self.view.frame;
    if (movedUp)
    {
        if (self.view.frame.origin.y != -kOFFSET_FOR_KEYBOARD){

        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
      }
  }
  else
  {
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
  }
        self.view.frame = rect;
        [UIView commitAnimations];
}
1

There are 1 best solutions below

0
On

Try keeping a BOOL keyboardIsUp which is true if the keyboard is up, and then when entering the function keyboardWillHide, ask if keyboardIsUp is true. If it's true, carry on. If it's false, exit the function:

-(void)keyboardWillHide 
{
    if (keyboardIsUp == NO)
        return;
    else
        //your code   

Your function will still be called twice, or more, but will only do its functionality once. Just make sure to set keyboardIsUp to YES and NO when appropriate.