当编辑开始时,这会很好地将您的 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];
}