我正在使用6.1模拟器测试我的iOS应用。当键盘可见时(在用户点击textView之后),我已经工作了几个小时将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];
}
}
您可以从上面的图片中看到,如果用户点击了textView,则scrollView不会滚动到正确的位置(您应该能够看到textView的文本内容)。
奇怪的是我手动尝试将scrollPoint的y偏移更改为不同的值,但它似乎对窗口滚动到的位置没有影响。 我做错了什么?
其他可能很重要的事情:
修改
我发现如果我将我的偏移量添加到contentInsets,如下所示:
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+50.0, 0.0);
视图将滚动到正确的位置。唯一的缺点是底部有额外的填充:
有更好的方法吗?
答案 0 :(得分: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];
}