添加新行时,将UITextView完全向下滚动

时间:2018-08-18 20:05:32

标签: swift uitextview

无论何时添加新行,我都希望将用户编写的文本居中。新行的检测工作正常:

var previousRect = CGRect.zero
func textViewDidChange(_ textView: UITextView) {
    let pos = textView.endOfDocument
    let currentRect = textView.caretRect(for: pos)
    self.previousRect = self.previousRect.origin.y == 0.0 ? currentRect : previousRect
    if(currentRect.origin.y > previousRect.origin.y){
        print("newline detected")

        //scroll down to center new line
    }
    previousRect = currentRect
}

要在我的UITextView中将新行居中,我现在想手动向下滚动尽可能多的内容(这是指滚动“太多”时将其重置为的点)。经验表明,视频总是有帮助的,因此:a demonstration of the problem on YouTube。您可以看到我总是需要向下滚动以使新行居中。 isScrollEnabled设置为true

到目前为止,我尝试过完全向下滚动的所有方式都无法完全正常工作,或者其工作“做得太好”,即向下滚动的次数超过了手动进行的次数。

示例:

//Didn't work at all
func scrollTextViewToBottom(textView: UITextView) {
    if textView.text.count > 0 {
        let location = textView.text.count - 1
        let bottom = NSMakeRange(location, 1)
        textView.scrollRangeToVisible(bottom)
    }
}

//Didn't work at all
let bottom = self.textView.contentSize.height - 
self.textView.bounds.size.height
self.textView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true)

//"Over"-scrolls 
textView.contentOffset = CGPoint(x: 0, y: textView.contentSize.height - textView.frame.size.height)

关于最后一个示例:如果我再次手动向下滚动然后停止,它会回到通常重置为的位置(如视频所示)。

我很想听听一些新想法。我真的无法解释为什么我发现的任何一种方式(即SO方式)都行不通。希望能有所帮助!

0 个答案:

没有答案