如何在调整keyboardWillBeShown / keyboardWillBeHidden的内容时阻止scrollview弹跳

时间:2013-11-23 22:53:37

标签: ios uiscrollview uitextfield

我有一个包含许多文本字段的滚动视图,包括一些位于同一Y位置的文本字段。我正在使用以下代码来调整scrollview的偏移/插入,以便活动文本字段始终可见 - 但如果用户已经在编辑字段,然后点击同一“行”中的另一个文本字段(相同的Y位置), scrollview弹跳/重新调整。无论如何要解决这个问题吗?

- (void)keyboardWillBeShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;

    UIView *activeField = [self.view findFirstResponder];

    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    aRect.size.height -= aRect.origin.y;
    aRect.origin.y = 0;

    CGPoint activeFieldOrigin = [activeField convertPoint:CGPointZero toView:self.view.window];

    if (!CGRectContainsPoint(aRect, activeFieldOrigin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeFieldOrigin.y-kbSize.height);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
}

我可以通过执行setContentOffset来阻止这种行为:使用动画= NO进行动画处理。所以我假设使用animated = YES它将实际工作踢到一个块或延迟执行实际集,然后当它/确实/实际去做那个时,重新显示立即将它重置为相同位置。

思想?

1 个答案:

答案 0 :(得分:0)

您可以存储scrollview的当前contentoffset,例如contentOffsetY = _scrollView.contentOffset.y;然后检查

if(contentOffsetY==_scrollView.contentOffset.y)
{
//then should not change scrollviews content offset
}
else
{
//change content offset
}