滚动视图上的xcode UITapGestureRecognizer直到第二次点击才调用

时间:2015-02-06 03:28:18

标签: xcode uiscrollview uigesturerecognizer

如果用户点击背景,我有以下代码来关闭键盘。如果滚动视图位于PointZero位置,它可以正常工作,但如果用户滚动视图然后选择文本视图,则在第二次背景点击之前它不会调用“dismissKeyboard”方法。

在第一次点击时(由于某种原因)移动滚动视图偏移以与滚动视图帧对齐到屏幕底部。第二次点击将关闭键盘并运行下面的代码。我知道它与scrollview有关。任何帮助将不胜感激。

由于

- (void)viewDidLoad {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    tapGesture.cancelsTouchesInView = NO;
    [_scrollView addGestureRecognizer:tapGesture];
}

-(void)dismissKeyboard {
    [self.view endEditing:YES];
}

- (void)keyboardWasShown:(NSNotification *)notification {
    scrollViewRect = _scrollView.contentOffset.y;

    NSDictionary* info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    keyboardSize.height += 10;
    CGFloat viewBottom = CGRectGetMaxY(self.scrollView.frame);

    if ([_itemNotes isFirstResponder]) {
        CGFloat notesBottom = CGRectGetMaxY(_itemNotes.frame);
        viewBottom -= notesBottom;
        if (viewBottom < keyboardSize.height) {
            keyboardSize.height -= viewBottom;

            CGPoint scrollPoint = CGPointMake(0.0, keyboardSize.height);

            [self.scrollView setContentOffset:scrollPoint animated:YES];
        }
        else {
            [self.scrollView setContentOffset:CGPointZero animated:YES];
        }
    }
    else {
        [self.scrollView setContentOffset:CGPointZero animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification *)notification {
    CGPoint scrollPoint = CGPointMake(0.0, scrollViewRect);
    [self.scrollView setContentOffset:scrollPoint animated:YES];
}

编辑: 所以我想出了一个解决方案,但似乎必须有一个更好的方法来处理这个问题。问题是因为我正在设置scrollView的contentOffset,以便contentSize超出屏幕边界。因此,第一次点击将scrollView contentOffset移回屏幕边界内,第二次点击正在执行点击手势。我将在下面发布我的解决方案,希望有人有更好的答案。

2 个答案:

答案 0 :(得分:0)

我假设必须有一个更好的解决方案,但我能够通过在键盘显示时扩展contentSize然后在隐藏键盘时将其缩小来解决问题。

设置浮动(scrollViewHeight)以保留重置的原始内容大小。

//add this right before setting the content offset
scrollViewHeight = _scrollView.contentSize.height;
_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width , scrollViewHeight + keyboardSize.height);

//add this right before reseting the content offset
_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width , scrollViewHeight);

看起来似乎必须有一种我不知道的更好的方式。我将不得不回过头来看看是否有另一种方法。

答案 1 :(得分:0)

我建议设置

_scrollView.layer.borderColor = [UIColor redColor].CGColor;
_scrollView.layer.borderWidth = 1;

这将显示您的滚动视图边界的确切位置,这可能不是您认为的位置,或者可能被其他内容覆盖。此外,当我打开键盘时,我通常将scrollview框架底部设置为键盘顶部。否则,您可能无法使用键盘下方的内容。不确定这是否与您的问题完全相关。