Uikeyboardwillhidenotification method call twice on scroll

I have a view with a UIScrollView and I have a lot UITextField

I close the keyboard when I touch the view and it works fine at the same time when I want to close the keyboard when I view the view. My problem is when I view the view that closes the keyboard, but it calls the (keyboardWillHide) method twice, which makes the problem related to the wrong screen setting. How can I prevent the method from being called twice?

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];
}

      

+3


source to share


1 answer


Try to keep BOOL keyboardIsUp true if keyboard is inserted and then when you enter keyboardWillHide function ask if keyboardIsUp is true. If that's true, go ahead. If it's wrong, exit the function:

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

      



Your function will still be called twice or more, but it will only execute its function once. Just remember to set the IsUp keyboard to YES and NO if necessary.

+1


source







All Articles