簡體   English   中英

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

[英]How to select all text that you can see in the NSTextView?

我想要一種方法,以編程方式只選擇邊界中的文本,並在窗口滾動或更改邊界時進行更改。

SelectAll不起作用。 我不想要整個文件。 我的目標是對窗口中的任何文本滾動進行反應,掃描關鍵詞並在第二個窗口中顯示上下文信息。

我提出了一個解決方案,誠然,這是一個黑客攻擊。 它使用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)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM