我已经为 UIScrollView 的问题苦苦挣扎了很长时间。
我有一个UIScrollVIew包含 aUITextView作为子视图。当我选择文本视图时,会弹出键盘。我想调整文本视图的大小以完全适合可用空间,并滚动滚动视图,以便文本视图恰好位于可见空间中(不被键盘隐藏)。
当键盘出现时,我调用一个方法来计算文本视图的适当大小,然后执行以下代码:
[UIView animateWithDuration:0.3
animations:^
{
self.textView.frame = frame;
}
];
[self.scrollView setContentOffset:CGPointMake(0,frame.origin.y) animated:YES];
Run Code Online (Sandbox Code Playgroud)
(这里的框架是文本视图的适当框架)。
不幸的是,滚动视图并不总是滚动到正确的位置,特别是当我选择文本视图时它已经处于非零垂直内容偏移处。我知道我设置的内容偏移量是正确的。
经过大量测试,我终于意识到发生的事情是动画完成后,滚动视图再次自动滚动。
这段代码确实有效:
UIView animateWithDuration:0.3
animations:^
{
self.textView.frame = frame;
}
completion:^(BOOL finished) {
[self.scrollView setContentOffset:CGPointMake(0, frame.origin.y) animated:YES];
}
];
Run Code Online (Sandbox Code Playgroud)
但这看起来很奇怪,因为滚动视图滚动到错误的位置,然后滚动到正确的位置。
有谁知道当文本视图框架完成其动画时如何防止滚动视图更改其内容偏移量?
我正在使用 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;
}
Run Code Online (Sandbox Code Playgroud)
([self updateViewLayout]是一种将文本视图返回到正确高度,并重置滚动视图内容大小,以及确保所有其他子视图正确定位的方法)。
不要调整文本视图的框架。您所需要做的就是滚动滚动视图。如果你滚动滚动视图动画,那么文本视图将向上滑动动画。只需执行以下操作:
[self.scrollView setContentOffset:CGPointMake(0, frame.origin.y) animated:YES];
Run Code Online (Sandbox Code Playgroud)
如果您需要滚动视图以特定速率滚动,则手动调整动画块中的内容偏移量。(我还没有测试过这一点,您可能需要调整动画标志,或者逐个逐个像素地执行内容偏移量)如果这不起作用的话)
[UIView animateWithDuration:0.3f
animations:^{
[self.scrollView setContentOffset:CGPointMake(0, frame.origin.y) animated:YES];
} ];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23092 次 |
| 最近记录: |