gpt4 book ai didi

ios - 在 UITextView 中滚动后获取可见文本的 NSRange

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:18 25 4
gpt4 key购买 nike

我正在尝试将滚动文本的位置保存在 UITextView 中,以便我可以在再次加载 ViewController 时返回到该位置。我有很长的字符串,所以我希望用户能够滚动到特定位置,然后稍后返回到该位置。

我正在使用 UITextView。 scrollRangeToVisible 函数自动滚动 TextView ,但我不知道如何获取用户看到的文本的 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)
}

}

关于ios - 在 UITextView 中滚动后获取可见文本的 NSRange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com