【问题标题】:How to select all text that you can see in the NSTextView?如何选择您可以在 NSTextView 中看到的所有文本?
【发布时间】:2017-01-24 08:10:12
【问题描述】:

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

SelectAll 将不起作用。我不想要整个文件。我的目标是对滚动到窗口中的任何文本做出反应,扫描它以查找关键词并在第二个窗口中显示上下文信息。

【问题讨论】:

  • 我对任何方法都持开放态度,而不仅仅是我所描述的那种。如果有办法只让边界中可见的线条片段,我还没有找到。
  • 你找到答案了吗?

标签: objective-c swift macos nstextview nslayoutmanager


【解决方案1】:

我想出了一个解决方案,诚然,这有点像 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)
        }
    }
}

【讨论】:

  • 我马上试试。另外:我认为这样的事情是另一个答案 (NSRange)glyphRangeForBoundingRectWithoutAdditionalLayout:(CGRect)bounds inTextContainer:(NSTextContainer *)container;然后使用字形索引访问字符索引中的范围,如果成功,我将继续处理并发布。谢谢你的上述。
  • 这里是一些感兴趣的先前帖子。 stackoverflow.com/questions/16675997/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 2019-06-07
  • 2020-05-26
  • 2011-06-23
相关资源
最近更新 更多