我一直在努力解决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]是一种方法,它将文本视图返回到正确的高度,并重置滚动视图内容大小,并确保所有其他子视图都正确定位).
解决方法
不要调整文本视图的框架.您需要做的就是滚动滚动视图.如果滚动滚动视图动画,则textView将向上滑动动画.只需执行以下操作:
[self.scrollView setContentOffset:CGPointMake(0,frame.origin.y) animated:YES];
如果你需要滚动视图以特定的速率滚动,那么手动调整动画块中的内容偏移量.(我没有测试过这个,你可能想要调整动画标记,或者逐步调整内容偏移一个像素时间,如果这不起作用)
[UIView animateWithDuration:0.3f animations:^{ [self.scrollView setContentOffset:CGPointMake(0,frame.origin.y) animated:YES]; } ];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。