我有UIScrollView,它有一些视图,包括UITextView。 UITextView比屏幕更大,并且有一些文本并且已禁用滚动。如果用户点击文本视图,我想将主滚动视图滚动到文本视图中光标的位置。我该怎么做?我尝试过使用selectedRange,但它似乎没有用。
答案 0 :(得分: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];
}
答案 1 :(得分:0)
我是这样做的:
- (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];
}
如果有人知道更好的解决方案,请写下答案,我会接受。