Это будет приятно прокрутить ваш UITextView к верхней части клавиатуры, когда начнется редактирование.Это также будет работать, если ваш UITextView имеет динамическую высоту (автогроу / авторазмер при наборе текста).Протестировано в iOS 7.
Вызовите метод наблюдателя клавиатуры и установите делегата UITextView для текущего класса:
- (void)viewDidLoad
{
...
[self observeKeyboard];
textView.delegate = (id)self;
}
Добавьте наблюдателя клавиатуры для UIKeyboardDidShowNotification и UIKeyboardWillShowNotification:
- (void)observeKeyboard
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}
Получить размер клавиатуры:
- (void)keyboardWillShow:(NSNotification *)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
_keyboardHeight = keyboardSize.height;
}
- (void)keyboardDidShow:(NSNotification *)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
_keyboardHeight = keyboardSize.height;
}
Когда UITextView начал редактирование или значение изменилось, вызовите scrollKeyboardToTextView
:
- (void)textViewDidBeginEditing:(UITextView *)textView
{
[self scrollKeyboardToTextView:textView];
}
- (void)textViewDidChange:(UITextView *)textView
{
[self scrollKeyboardToTextView:textView];
}
Прокрутите UITextView с анимацией к верхней части клавиатуры:
- (void)scrollKeyboardToTextView:(UITextView *)textView
{
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, _keyboardHeight, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
CGRect aRect = self.view.frame;
aRect.size.height -= _keyboardHeight;
CGPoint origin = textView.frame.origin;
origin.y -= self.scrollView.contentOffset.y;
origin.y += textView.frame.size.height;
CGPoint scrollPoint = CGPointMake(0.0, textView.frame.origin.y + textView.frame.size.height - (aRect.size.height));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}