如何滚动到UitextView的顶部



我下面的代码一直滚动到文本字段的底部。我该如何进行反向,并使代码函数滚动到文本字段的开头?

let bottom = NSMakeRange(theTextView.text.characters.count - 1, 1)
theTextView.scrollRangeToVisible(bottom)

最明显的解决方案是将NSMakeRangelocation参数设置为0,而不是theTextView.text.characters.count - 1

let bottom = NSRange(location: 0, length: 1)

更好的方法是注意UITextView扩展了UIScrollView。因此,您可以设置contentOffset

theTextView.contentOffset = .zero

如果您想为滚动动画,请使用:

theTextView.setContentOffset(.zero, animated: true)

您可以使用此扩展名:

extension UIScrollView {
    func scrollToTop() {
        let desiredOffset = CGPoint(x: 0, y: -contentInset.top)
        setContentOffset(desiredOffset, animated: true)
    }
}

用法:

textView.scrollToTop()

最新更新