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

标签 objective-c swift macos nstextview nslayoutmanager

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

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/

相关文章:

ios - 遍历数组然后将当前对象与字符串进行比较

ios - iphone 6 及更高版本的 Xcode 约束和大小类

objective-c - IBOutlet 声明?

ios - UIContextMenu Action Provider 在项目上放置不需要的复选标记图标

iOS:如何在 Swift 中为 View 创建顶部/底部圆角和阴影

cocoa - CGBitmapContext 获取像素值 Leopard 与 SnowLeopard 混淆

objective-c - UIView 方向不正确

java - 无法在 Mac OS Yosemite 上安装 JDK 8u25

swift - 调整大小后的图像周围有白色边框

ios - 如何有效地将 SKS 中的子节点与场景中的代码链接起来