キーボードが選択したテキスト入力を非表示にするたびにビューを自動的にスクロールする機能を実装しました (私のものとチュートリアルのものは実際には同じです)。
残念ながら、望ましくない動作があります。私の scrollView のcontentSize
プロパティは、キーボードの高さによって増加します。そのため、キーボードがまだ表示されている場合はビューをスクロールできますが、適切なコンテンツの下に空白が表示されます。これは避けたいことです。これはプロパティの変更が原因であることを認識しているcontentInset
ため、副作用なしでこれを行う別の方法があるかもしれません。
最初に、 と のオブザーバーを登録UIKeyboardDidShowNotification
しUIKeyboardWillHideNotification
ます。
- (void)registerKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}
この関数は で呼び出されviewWillAppear
ます。メソッドkeyboardWasShown
とkeyboardWillBeHidden
外観は次のとおりです。
- (void)keyboardWasShown:(NSNotification *)notification
{
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
CGRect rect = self.view.frame;
rect.size.height -= kbSize.height;
if(!CGRectContainsPoint(rect, activeField.frame.origin)) {
CGPoint scrollPoint = CGPointMake(0.0, 2*activeField.frame.size.height+activeField.frame.origin.y-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWillBeHidden:(NSNotification *)notification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
先ほども書きましたが、基本的にはAppleのソリューションです。