我遇到過類似的問題,包括「如果我設置動畫爲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。作品,但:( –