我有一个带有UITextView的ViewController占用整个视图,顶部有一个导航栏。几乎像Apple的“Notes”应用程序。我想要实现的是在编辑开始或编辑时保持textview的光标可见。
我能够获得光标的CGPoint
,但我很难计算滚动点。我怎样才能做到这一点?
由于
当textview开始编辑时
- (void)keyboardDidShow:(NSNotification*)aNotification {
// Keyboard
NSDictionary *info = [aNotification userInfo];
CGRect keyPadFrame = [[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:self.view];
CGSize keyboardSize = keyPadFrame.size;
kbSize = keyboardSize;
[self scrollToCursor];
}
编辑textview时
- (void)textViewDidChange:(UITextView *)textView {
// Scroll to cursor
[self scrollToCursor];
}
滚动到光标方法
- (void)scrollToCursor {
// View
CGRect viewBounds = self.view.bounds;
CGRect visibleViewBounds = CGRectMake(viewBounds.origin.x,
viewBounds.origin.y + (self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height),
viewBounds.size.width,
viewBounds.size.height - (kbSize.height + self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height));
// TextView
CGPoint textViewOrigin = [self.view convertRect:self.noteTextView.frame fromView:self.noteTextView.superview].origin;
// Cursor
CGPoint textViewCursor = [self.noteTextView caretRectForPosition:self.noteTextView.selectedTextRange.start].origin;
CGPoint cursorPoint = CGPointMake((textViewCursor.x + textViewOrigin.x), (textViewCursor.y - self.noteTextView.contentOffset.y));
// Scroll to point
if (!CGRectContainsPoint(visibleViewBounds, CGPointMake(cursorPoint.x, cursorPoint.y + 25/*25 for cursor's height*/))) {
[self.noteTextView setContentOffset:CGPointMake(0, 0)/*How to calculate??*/ animated:YES];
}
}
答案 0 :(得分:3)
这根本没有经过测试,但这是我第一次尝试。
通过聆听KeyboardWillChangeFrameNotification
获取键盘高度CGRect keyboardFrame;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
- (void)keyboardWillChange:(NSNotification *)notification {
keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardFrame = [self.view convertRect:keyboardRect fromView:nil];
}
这将为您提供键盘高度。
然后获得屏幕高度:
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
CGFloat screenHeight = screenSize.height;
然后,如果您知道光标的CGPoint,请执行以下操作:
CGFloat keyboardTop = (screenHeight - (keyboardFrame.size.height + <padding if you want it>));
if (currentCursorPosition.y > keyboardTop)
{
[self.noteTextView setContentOffset:CGPointMake(0, (cursorPoint.y - (viewBounds.size.height - kbSize.height)) + self.noteTextView.contentOffset.y + 25);
}
理想情况下,这应该将光标保持在键盘的顶部,然后在向下移动光标时滚动。
答案 1 :(得分:0)
为了您的理智,只需使用图书馆。
这是一个好人:https://github.com/hackiftekhar/IQKeyboardManager
迦太基:
github“ hackiftekhar / IQKeyboardManager”
CocoaPods:
pod'IQKeyboardManagerSwift','6.3.0'
或
pod'IQKeyboardManager','3.3.7'#iOS7