在iOS7或TextKit中使用什么来代替scrollRangeToVisible

在以前的iOS版本中,我的UITextView将使用滚动到底部

 [displayText scrollRangeToVisible:NSMakeRange(0,[displayText.text length])]; 

要么

 CGFloat topCorrect = displayText.contentSize.height -[displayText bounds].size.height; topCorrect = (topCorrect<0.0?0.0:topCorrect); displayText.contentOffset = (CGPoint){.x=0, .y=topCorrect}; 

但是前者现在会有一个怪异的效果,就是从长长的文本顶部开始,每当我将文本添加到视图时,都会将滚动animation到底部。 添加文本时是否有办法popup到文本底部?

 textView.scrollEnabled = NO; [textView scrollRangeToVisible:NSMakeRange(textView.text.length - 1,0)]; textView.scrollEnabled = YES; 

这在iOS 7.1.2中对我很有用。

我相信这是iOS 7中的一个bug。在UITextView上切换scrollEnabled似乎可以解决这个问题:

 [displayText scrollRangeToVisible:NSMakeRange(0,[displayText.text length])]; displayText.scrollEnabled = NO; displayText.scrollEnabled = YES; 

对于未来的旅行者来说,build立@ mikeho的post,我发现了一些为我创造奇迹的东西,但是更简单一些。

1)确保你的UITextViewcontentInset设置正确,你的firstResponder()已经是firstResponder()
2)在我的插件准备好之后,光标被激活,我调用以下函数:

 private func scrollToCursorPosition() { let caret = textView.caretRectForPosition(textView.selectedTextRange!.start) let keyboardTopBorder = textView.bounds.size.height - keyboardHeight! // Remember, the y-scale starts in the upper-left hand corner at "0", then gets // larger as you go down the screen from top-to-bottom. Therefore, the caret.origin.y // being larger than keyboardTopBorder indicates that the caret sits below the // keyboardTopBorder, and the textView needs to scroll to the position. if caret.origin.y > keyboardTopBorder { textView.scrollRectToVisible(caret, animated: true) } } 

我认为你的参数在NSMakeRange是相反的。 位置是第一个,那么你要select多less( 长度 )。

 NSMakeRange(0,[displayText.text length]) 

…将创build一个从第0个(第一个?)字符开始并select整个string的select。 要滚动到底部,您可能只想在最后select一个字符。

这在iOS SDK 7.1中适用于Xcdoe 5.1.1。

 [textView scrollRangeToVisible:NSMakeRange(textView.text.length - 1,0)]; textView.scrollEnabled = NO; textView.scrollEnabled = YES; 

我这样做,因为我以编程方式添加文本,文本视图停留在底部,如terminal或命令行输出。

最好的方法是设置UITextView的边界。 它不会触发滚动,并立即重新定位可见的效果。 您可以通过查找插入符号的位置然后重新定位来完成此操作:

 - (void)userInsertingNewText { UITextView *textView; // find out where the caret is located CGRect caret = [textView caretRectForPosition:textView.selectedTextRange.start]; // there are insets that offset the text, so make sure we use that to determine the actual text height UIEdgeInsets textInsets = textView.textContainerInset; CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom; // only set the offset if the caret is out of view if (textViewHeight < caret.origin.y) { [self repositionScrollView:textView newOffset:CGPointMake(0, caret.origin.y - textViewHeight)]; } } /** This method allows for changing of the content offset for a UIScrollView without triggering the scrollViewDidScroll: delegate method. */ - (void)repositionScrollView:(UIScrollView *)scrollView newOffset:(CGPoint)offset { CGRect scrollBounds = scrollView.bounds; scrollBounds.origin = offset; scrollView.bounds = scrollBounds; }