滚动

时间:2015-06-15 12:19:21

标签: ios objective-c uiscrollview uikeyboard

我有一个使用UIScrollView的视图,并且有很多UITextField我在触摸视图时关闭了键盘,它在我滚动视图时想要关闭键盘的同时工作正常。我的问题是,当我滚动视图时它正在关闭键盘,但它调用方法(keyboardWillHide)两次,这对我来说设置屏幕错误是一个问题。如何防止两次调用该方法?

我的代码:

- (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 个答案:

答案 0 :(得分:1)

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.