【发布时间】:2012-02-14 03:40:47
【问题描述】:
我一直在为 UIScrollView 的问题苦苦挣扎。
我有一个UIScrollVIew,其中包含一个UITextView 作为子视图。当我选择文本视图时,会弹出一个键盘。我想调整文本视图的大小以完全适合可用空间,并滚动滚动视图以使文本视图准确定位在可见空间中(不被键盘隐藏)。
当键盘出现时,我调用一个方法来计算文本视图的适当大小,然后执行以下代码:
[UIView animateWithDuration:0.3
animations:^
{
self.textView.frame = frame;
}
];
[self.scrollView setContentOffset:CGPointMake(0,frame.origin.y) animated:YES];
(这里的框架是文本视图的适当框架)。
不幸的是,滚动视图并不总是滚动到正确的位置,尤其是当我选择文本视图时它已经处于非零垂直内容偏移量时。我知道我设置的内容偏移是正确的。
经过大量的测试,我终于意识到发生了什么是动画完成后,滚动视图又自动滚动了。
此代码确实有效:
UIView animateWithDuration:0.3
animations:^
{
self.textView.frame = frame;
}
completion:^(BOOL finished) {
[self.scrollView setContentOffset:CGPointMake(0, frame.origin.y) animated:YES];
}
];
但它看起来很奇怪,因为滚动视图滚动到错误的位置,然后滚动到正确的位置。
有谁知道当文本视图框架完成其动画时,我可以如何防止滚动视图更改其内容偏移量?
我正在使用 iOS 5.0 进行测试。
这是我发现可行的解决方案。我仍然不完全了解发生了什么,可能与我的弹簧和支柱的设置方式有关。基本上,我将滚动视图内容的大小缩小了与文本视图缩小的量相同。
- (void)keyboardDidShow:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
// Get the height of the keyboard
CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
kbRect = [self.view convertRect:kbRect fromView:nil];
CGSize kbSize = kbRect.size;
// Adjust the height of the text view to fit in the visible view
CGRect frame = self.textView.frame;
int visibleHeight = self.view.frame.size.height;
visibleHeight -= kbSize.height;
frame.size.height = visibleHeight;
// Get the new scroll view content size
CGSize contentSize = self.scrollView.contentSize;
contentSize.height = contentSize.height - self.textView.frame.size.height + frame.size.height;
[UIView animateWithDuration:0.1
animations:^
{
self.textView.frame = frame;
// Note that the scroll view content size needs to be reset, or the scroll view
// may automatically scroll to a new position after the animation is complete.
self.scrollView.contentSize = contentSize;
[self.scrollView setContentOffset:CGPointMake(0, frame.origin.y) animated:YES];
}
];
// Turn off scrolling in scroll view
self.scrollView.scrollEnabled = NO;
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
// Update the view layout
[UIView animateWithDuration:0.3 animations:^
{
self.scrollView.contentOffset = CGPointZero;
[self updateViewLayout];
}
];
// Turn on scrolling in the scroll view
self.scrollView.scrollEnabled = YES;
}
([self updateViewLayout] 是一种将文本视图返回到正确高度、重置滚动视图内容大小以及确保所有其他子视图正确定位的方法。
【问题讨论】:
标签: ios uiscrollview