[英]How to scroll to top of UITextView?
我下面的代碼一直滾動到文本字段的底部。 我該如何做相反的事情,並具有代碼功能來滾動到文本字段的開頭?
let bottom = NSMakeRange(theTextView.text.characters.count - 1, 1)
theTextView.scrollRangeToVisible(bottom)
最明顯的解決方案是將NSMakeRange
的location
參數設置為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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.