gpt4 book ai didi

iOS:将 View 滚动到 TextView 中的当前光标位置

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:52 29 4
gpt4 key购买 nike

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

最佳答案

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

- (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];
}

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com