gpt4 book ai didi

swift - 如何检测 AppKit 中 TextView 中的换行符?

转载 作者:搜寻专家 更新时间:2023-11-01 05:31:56 25 4
gpt4 key购买 nike

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

问题是,如果有问题的字符范围跨越两行,边界矩形将在高度和宽度上覆盖它们,所以我需要为 TextView 中的每一行文本执行此操作。

问题 NSTextViewNSTextStorageNSTextContainer 中的字符串属性返回没有换行符的字符串 ("\n")。我怎样才能:

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

2) 使用其他技术遍历 TextView 的行?

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

我的 View Controller 代码:


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 - 如何检测 AppKit 中 TextView 中的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56924942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com