我想要一种以编程方式仅选择边界中的文本并在窗口滚动或更改边界时进行更改的方法。
SelectAll
不管用。我不想要整个文件。我的目标是对滚动到窗口中的任何文本做出反应,扫描它以查找关键词并在第二个窗口中显示上下文信息。
我想要一种以编程方式仅选择边界中的文本并在窗口滚动或更改边界时进行更改的方法。
SelectAll
不管用。我不想要整个文件。我的目标是对滚动到窗口中的任何文本做出反应,扫描它以查找关键词并在第二个窗口中显示上下文信息。
我想出了一个解决方案,诚然,这有点像 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)
}
}
}