2014-09-06 74 views
0

我正在使用6.1模拟器测试我的iOS应用程序。当键盘可见时(用户点击textView后),我一直在工作数小时以将我的scrollView滚动到正确的位置。我曾尝试下面的答案标志着这个网页上是正确的:iOS:scrollView在键盘可见时不滚动到正确位置

How do I scroll the UIScrollView when the keyboard appears?

这是我目前有:

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

} 

enter image description here

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

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

其它东西可能是重要的:

  • 我有自动布局关闭(以使得用户可以在该视图中垂直滚动)。
  • TextView的不可滚动(它是调整大小以适应其内容)

编辑

我发现,如果我加入我的偏移量,contentInsets如下:

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+50.0, 0.0); 

视图将滚动到正确的位置。唯一的缺点是,有微胖底部:

enter image description here

有没有更好的方式来做到这一点?

回答

1

我用这个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]; 
} 
相关问题