iOS:滚动视图到文本视图中的当前光标位置
Posted
技术标签:
【中文标题】iOS:滚动视图到文本视图中的当前光标位置【英文标题】:iOS: Scroll view to the current cursor position in text view 【发布时间】:2014-04-16 13:34:26 【问题描述】:我有 UIScrollView,它有一些视图,包括 UITextView。 UITextView 比屏幕大,有一些文本,并且禁用了滚动。如果用户点击文本视图,我想将我的主滚动视图滚动到文本视图中光标的位置。我该怎么做?我尝试使用 selectedRange 但它似乎不起作用。
【问题讨论】:
【参考方案1】:这是我的一个更复杂的解决方案:
- (void)scrollView:(UIScrollView *)scrollView scrollToTextInput:(UIResponder *)responder
if (!responder || ![responder conformsToProtocol:@protocol(UITextInput)] || ![responder isKindOfClass:[UIView class]])
return;
UIView<UITextInput> *textInput = (UIView<UITextInput> *)responder;
UIView *nextView = textInput;
while (nextView && (nextView != scrollView))
nextView = [nextView superview];
if (!nextView)
// Oh, this view is not from our `scrollView`.
return;
CGRect cursorRect = [textInput caretRectForPosition:textInput.selectedTextRange.start];
CGPoint cursorPoint = CGPointMake(CGRectGetMidX(cursorRect), CGRectGetMidY(cursorRect));
cursorPoint = [scrollView convertPoint:cursorPoint fromView:textInput];
CGFloat contentHeight = scrollView.contentSize.height;
CGFloat containerHeight = scrollView.frame.size.height;
CGFloat topInset = scrollView.contentInset.top;
CGFloat bottomInset = scrollView.contentInset.bottom;
CGFloat verticalInsets = scrollView.contentInset.top + scrollView.contentInset.bottom;
CGFloat offsetY = cursorPoint.y - (containerHeight - verticalInsets) / 2.f;
offsetY = MIN(MAX(offsetY, topInset), contentHeight - containerHeight + verticalInsets);
[scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, offsetY) animated:YES];
【讨论】:
【参考方案2】:我是这样做的:
- (void)textViewDidBeginEditing:(UITextView *)textView
[self performSelector:@selector(scrollToCursorPosition:) withObject:textView afterDelay:0.05f];
- (void)scrollToCursorPosition:(UITextView *)textView
UITextRange *range = textView.selectedTextRange;
UITextPosition *position = range.start;
CGRect cursorRect = [textView caretRectForPosition:position];
CGPoint cursorPoint = CGPointMake(textView.frame.origin.x + cursorRect.origin.x, textView.frame.origin.y + cursorRect.origin.y);
[self setContentOffset:CGPointMake((cursorPoint.x - 10) * self.zoomScale, (cursorPoint.y - 10) * self.zoomScale) animated:NO];
如果有人知道更好的解决方案,请写下答案,我会接受。
【讨论】:
以上是关于iOS:滚动视图到文本视图中的当前光标位置的主要内容,如果未能解决你的问题,请参考以下文章