我遇到过类似的问题,包括“如果我设置动画为NO,一切都按预期工作”部分。
事实证明,在iOS 6上,UITextView自动滚动其最近的父级UIScrollView,使其成为第一响应者时可见。在iOS 7上没有这样的行为。 UIScrollView似乎在两次调用scrollRectToVisible几乎同时时感到困惑。
在iOS 6上,我显式调用scrollRectToVisible将被忽略大部分时间。它只会滚动,使UITextView的第一行可见(自动滚动),而不像iOS 7那样。
要测试它,在Xcode 5中创建一个新的单视图应用程序,将其设置为部署目标为6.0,并使用下面的代码为ViewController.m。在iOS 6.1模拟器中运行它,滚动以隐藏UITextView并点击屏幕上的任意位置。您可能需要重试几次,但在大多数情况下,只会显示第一行。如果重新启用WORKAROUD,则将UITextView嵌入到其自己的UIScrollView中,并且对scrollRectToVisible的调用按预期工作。
#import "ViewController.h"
//#define WORKAROUND
@interface ViewController()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITextView *textView;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTap)]];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 240)];
self.scrollView.contentSize = CGSizeMake(320, 400);
self.scrollView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:self.scrollView];
#ifdef WORKAROUND
UIScrollView* dummyScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 280, 280, 100)];
self.textView = [[UITextView alloc] initWithFrame:dummyScrollView.bounds];
[dummyScrollView addSubview:self.textView];
[self.scrollView addSubview:dummyScrollView];
#else
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 280, 280, 100)];
[self.scrollView addSubview:self.textView];
#endif
self.textView.backgroundColor = [UIColor grayColor];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewTap
{
if (self.textView.isFirstResponder) {
[self.textView resignFirstResponder];
}
else {
[self.textView becomeFirstResponder];
}
}
- (void)keyboardWasShown:(NSNotification*)aNotification
{
#ifdef WORKAROUND
[self.scrollView scrollRectToVisible:CGRectInset(self.textView.superview.frame, 0, -10) animated:YES];
#else
[self.scrollView scrollRectToVisible:CGRectInset(self.textView.frame, 0, -10) animated:YES];
#endif
}
@end
还没有想通了这一点,但我必须把它完成,所以我刚开始一个计时器,并滚动它自己,直到它在正确的位置,使用setContentOffset W /动画:NO。作品,但:( –