iOS:当键盘可见时,滚动视图未滚动到正确位置

iOS:当键盘可见时,滚动视图未滚动到正确位置,ios,objective-c,uiscrollview,keyboard,Ios,Objective C,Uiscrollview,Keyboard,我正在使用6.1模拟器测试我的iOS应用程序。我已经工作了好几个小时,以便在键盘可见时(在用户单击textView后)将scrollView滚动到正确的位置。我尝试了以下在本页上标记为正确的答案: 这就是我目前拥有的: - (void)keyboardWasShown:(NSNotification*)aNotification { NSLog(@"keyboardWasShown"); NSDictionary* info = [aNotification userInfo

我正在使用6.1模拟器测试我的iOS应用程序。我已经工作了好几个小时,以便在键盘可见时(在用户单击textView后)将scrollView滚动到正确的位置。我尝试了以下在本页上标记为正确的答案:

这就是我目前拥有的:

- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSLog(@"keyboardWasShown");

    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;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, self.activeView.frame.origin) ) {
        NSLog(@"scrollToView");
        CGPoint scrollPoint = CGPointMake(0.0, self.stepDescriptionField.frame.origin.y-kbSize.height);
        NSLog(@"scrollPoint: %f", scrollPoint.y);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }

}

从上面的图像可以看出,如果用户单击textView,则scrollView不会滚动到正确的位置(您应该能够看到textView的文本内容)

奇怪的是,我手动尝试将scrollPoint的y偏移量更改为不同的值,但这似乎对窗口滚动到的位置没有影响我做错了什么?

其他重要事项:

  • 我已关闭自动布局(以便用户可以在此视图中垂直滚动)
  • textView不可滚动(已调整大小以适应其内容)
编辑

我发现,如果我将偏移量添加到ContentInset,如下所示:

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+50.0, 0.0);
视图将滚动到正确的位置。唯一的缺点是底部有额外的填充物:


有更好的方法吗?

我将其与UITextField而不是UITextView一起使用,但我相信它仍然可以工作。这允许我将文本字段直接定位在键盘上方

keyboardWillShow是
NSNotificationCenter
接收
UIKeyboardWillShowNotification

-(void) keyboardWillShow:(NSNotification *)note
{
// Get the keyboard size
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

// Start animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];


// Get Keyboard height and subtract the screen height by the origin of the textbox and height of text box to position textbox right above keyboard
self.scrollView.contentOffset = CGPointMake(0,keyboardBounds.size.height-([UIScreen mainScreen].bounds.size.height - commentBox.frame.origin.y - commentBox.frame.size.height));

[UIView commitAnimations];
}