如何选择您在NSTextView中可以看到的所有文本?

时间:2016-09-16 07:11:16

标签: objective-c swift macos nstextview nslayoutmanager

我想要一种方法,以编程方式只选择边界中的文本,并在窗口滚动或更改边界时进行更改。

utf-8无效。我不想要整个文件。我的目标是对窗口中的任何文本滚动进行反应,扫描关键词并在第二个窗口中显示上下文信息。

1 个答案:

答案 0 :(得分:0)

我提出了一个解决方案,诚然,这是一个黑客攻击。它使用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)
        }
    }
}