我正在使用6.1模擬器測試我的iOS應用程序。當鍵盤可見時(用戶點擊textView後),我一直在工作數小時以將我的scrollView滾動到正確的位置。我曾嘗試下面的答案標誌着這個網頁上是正確的:iOS:scrollView在鍵盤可見時不滾動到正確位置
How do I scroll the UIScrollView when the keyboard appears?
這是我目前有:
- (void)keyboardWasShown:(NSNotification*)aNotification {
NSLog(@"keyboardWasShown");
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, self.activeView.frame.origin)) {
NSLog(@"scrollToView");
CGPoint scrollPoint = CGPointMake(0.0, self.stepDescriptionField.frame.origin.y-kbSize.height);
NSLog(@"scrollPoint: %f", scrollPoint.y);
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
您可以從如上面的圖片看用戶點擊textView,scrollView不會滾動到正確的位置(您應該能夠看到textView的文本內容)。
奇怪的是,我手動嘗試將scrollPoint的y偏移量更改爲不同的值,但它似乎對窗口滾動到的位置沒有影響。 我在做什麼錯?
其它東西可能是重要的:
- 我有自動佈局關閉(以使得用戶可以在該視圖中垂直滾動)。
- TextView的不可滾動(它是調整大小以適應其內容)
編輯
我發現,如果我加入我的偏移量,contentInsets如下:
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+50.0, 0.0);
視圖將滾動到正確的位置。唯一的缺點是,有微胖底部:
有沒有更好的方式來做到這一點?