【问题标题】:How to detect line breaks in TextView in AppKit?如何在 AppKit 中检测 TextView 中的换行符?
【发布时间】:2019-11-17 09:06:52
【问题描述】:

总体思路:在NSScrollView(包含NSTextView)的文本段落中突出显示字符组。我从NSLayoutManager.boundingRect() 获取所选字符的边界矩形,并创建CAShapeLayer 并用其坐标/大小代替字符。

问题是如果有问题的字符范围跨越两行,边界矩形会在高度和宽度上覆盖它们,所以我需要对文本视图中的每一行文本都这样做。

有问题的问题: NSTextViewNSTextStorageNSTextContainer 中的字符串属性返回不带换行符的字符串 ("\n")。我该怎么做:

1) 找到带有换行符的文本视图的实际文本值?

2) 使用其他技术来遍历文本视图的行?

3) 使用其他库来完成我的总体想法?

我的视图控制器的代码:


import Cocoa

class ViewController: NSViewController {


    @IBOutlet weak var textView: NSTextView!
    @IBOutlet weak var shapeView: NSView!


    override func viewDidLoad() {
        super.viewDidLoad()

        shapeView.wantsLayer = true

        textView.string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    }


    @IBAction func checkButtonPressed(sender: NSButton) {

        let range = NSMakeRange(2, 5) //Creating a makeshift range for testing purposes
        let layoutManager = textView.layoutManager
        var textRect = NSRect()

        //Accessing bounding rectangle of the chosen characters
        textRect = (layoutManager?.boundingRect(forGlyphRange: range, in: textView.textContainer!))!

        //Creating a parent layer and assigning it as the main layer of the shape view
        let parentShapeLayer = CAShapeLayer()
        shapeView.layer = parentShapeLayer

        //Creating an actual rectangle - CAShapeLayer
        let shapeLayer = CAShapeLayer()
        parentShapeLayer.addSublayer(shapeLayer)
        parentShapeLayer.isGeometryFlipped = true
        shapeLayer.frame = textRect
        shapeLayer.backgroundColor = NSColor.yellow.cgColor

        if let string = textView.textStorage?.string {

            for var char in string {
                if (char == "\n") {
                    print(char) //Does not print anything
                }
            }
        }

    }


    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

P.S.我知道 NSLayoutManager 有方法 drawBackground() 并且我无法找到它需要的上下文,但这是一个不同的问题。

【问题讨论】:

标签: swift macos line-breaks appkit nstextview


【解决方案1】:

我找到了一个概念性的解决方法:我为单个字符而不是字符组绘制矩形,因此避免了换行检测。不是最佳的,但有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2012-07-15
    • 2016-02-16
    • 1970-01-01
    相关资源
    最近更新 更多