我想要一种以编程方式仅选择边界中的文本并随着窗口滚动或更改边界而更改的方法。
SelectAll
将不起作用。我不想要整个文档。我的目标是对窗口中滚动到 View 中的任何文本使用react,扫描其中的关键词并在第二个窗口中显示上下文信息。
最佳答案
我想出了一个解决方案,诚然,它有点像 hack。它使用 textView 的内容偏移量、内容高度和内容框架高度来估计可见文本的开始和结束索引。答案只是一个估计,因为自动换行是不可预测的。结果通常是实际可见文本的 ±10 个字符。您可以通过在开始/结束偏移量中添加/减去几个字符的缓冲区来对此进行补偿,这将确保您的 textView 文本的子字符串肯定包含可见文本,并且在开头和结尾只有几个额外的字符结束。
我希望这个答案对您(或其他人)有所帮助,或者至少能激发您的灵感,以提出能够满足您确切需求的解决方案。
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var textView: UITextView!
let textViewText = "Here's to the crazy ones. The misfits. The rebels. The trouble-makers. The round pegs in the square holes. The ones who see things differently. They're not fond of rules, and they have no respect for the status-quo. You can quote them, disagree with them, glorify, or vilify them. But the only thing you can't do is ignore them. Because they change things. They push the human race forward. And while some may see them as the crazy ones, we see genius. Because the people who are crazy enough to think they can change the world, are the ones who do."
override func viewDidLoad() {
super.viewDidLoad()
textView.text = textViewText
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let textViewContentHeight = Double(textView.contentSize.height)
let textViewFrameHeight = Double(textView.frame.size.height)
let textViewContentOffset = Double(textView.contentOffset.y)
let textViewCharacterCount = textViewText.characters.count
let startOffset = Int((textViewContentOffset / textViewContentHeight) * Double(textViewCharacterCount))
// If the user scrolls quickly to the bottom so that the text is completely off the screen, we don't want to proceed
if startOffset < textViewCharacterCount {
let endIndex = Int(((textViewContentOffset + textViewFrameHeight) / textViewContentHeight) * Double(textViewCharacterCount))
var endOffset = endIndex - textViewCharacterCount
if endIndex > textViewCharacterCount {
endOffset = 0
}
let visibleString = textViewText.substringWithRange(textViewText.startIndex.advancedBy(startOffset)..<textViewText.endIndex.advancedBy(endOffset))
print(visibleString)
}
}
}
关于objective-c - 如何选择您可以在 NSTextView 中看到的所有文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39525687/