我正在尝试将滚动文本的位置保存在UITextView
这样我就可以在加载时返回到该位置ViewController
再次。我有很长的字符串,所以我希望用户能够滚动到特定位置,然后稍后返回到该位置。
我正在使用UITextView
。 scrollRangeToVisible 函数自动滚动文本视图,但我不知道如何获取用户正在看到的文本的 NSRange。这是解决这个问题的最佳方法吗?我尝试使用setContentOffset
功能,但似乎没有做任何事情。
任何帮助表示赞赏。谢谢!
这里有一个小扩展UITextView
使用它的characterRange(at:)
函数代替。它还添加了一个计算属性来返回当前可见的文本:
extension UITextView {
private var firstVisibleCharacterPosition: UITextPosition? {
// ⚠️ For some reason `characterRange(at:)` returns nil for points with a low y value.
guard let scrolledPosition = characterRange(at: contentOffset)?.start else {
return beginningOfDocument
}
return scrolledPosition
}
private var lastVisibleCharacterPosition: UITextPosition? {
return characterRange(at: bounds.max)?.end
}
/// The range of the text that is currently displayed within the text view's bounds.
var visibleTextRange: UITextRange? {
guard
let first = firstVisibleCharacterPosition,
let last = lastVisibleCharacterPosition else {
return nil
}
return textRange(from: first, to: last)
}
/// The string that is currently displayed within the text view's bounds.
var visibleText: String? {
guard let visibleTextRange = visibleTextRange else {
return nil
}
return text(in: visibleTextRange)
}
}
我在上面的代码中使用了这些简写属性:
extension CGRect {
var min: CGPoint {
return .init(x: minX, y: minY)
}
var max: CGPoint {
return .init(x: maxX, y: maxY)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)