OStack程序员社区-中国程序员成长平台

标题: iOS: ScrollView 到 TextView 中的当前光标位置 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 21:44
标题: iOS: ScrollView 到 TextView 中的当前光标位置

我有 UIScrollView,它有一些 View ,包括 UITextView。 UITextView 比屏幕大,有一些文本,并且禁用了滚动。如果用户点击 TextView ,我想将我的主 ScrollView 滚动到 TextView 中光标的位置。我该怎么做?我尝试使用 selectedRange 但它似乎不起作用。



Best Answer-推荐答案


这是我的一个更复杂的解决方案:

- (void)scrollViewUIScrollView *)scrollView scrollToTextInputUIResponder *)responder
{
    if (!responder || ![responder conformsToProtocolprotocol(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];
}

关于iOS: ScrollView 到 TextView 中的当前光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23111065/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4