.
我想做一个文本编辑器,可以预览降价文件。
当前状态
:
读/写文本文件工作正常。
问题:
这是我的密码:
向下导入//md转换库
class Document: NSDocument {
var string = ""
var ref: NSTextView
override init() {
self.ref = NSTextView()
super.init()
}
override class var autosavesInPlace: Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
// creates a new windowController on the fly when a new file is openend. That creates the new window...
let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as! NSWindowController
// the windowController contains a viewController
self.addWindowController(windowController)
// create reference to the textView inside the window we just created by opening the new file...
let vc = windowController.contentViewController as! ViewController
// THIS DOES NOT SEEM TO WORK
self.ref = vc.textView
}
override func data(ofType typeName: String) throws -> Data {
// SAVE BACK TO FILE
if let vc = self.windowControllers[0].contentViewController as? ViewController {
return vc.textView.string.data(using: String.Encoding.utf8) ?? Data()
}
else {
return Data()
}
}
override func read(from data: Data, ofType typeName: String) throws {
do {
let s = try String(data: data, encoding: .utf8)
let down = Down(markdownString: s!)
let fancyString = try! down.toAttributedString()
//self.ref.insertText(fancyString, replacementRange: NSRange(location: 0, length: 10))
self.ref.insertText("It might be working...", replacementRange: NSRange(location: 0, length: 10))
}
}
}
以下是我认为正在发生的事情:
为了构建这个代码,我需要分配一个
NSTextView()
实例到
self.ref
在里面
init()
makeWindowControllers()
,但这似乎不起作用。
我希望看到
It might be working...
有什么想法吗?
更新
感谢@Willeke提出这个问题。我以为
makeWindowControllers()
是第一个打电话的。结果是
read()
被称为然后
makeWindowControllers()
所以我可以分配
var fancyString:NSAttributedString = NSAttributedString(string: "hello")
作为类变量。然后设置
fancyString
从中的文件内容
并在中更新textView
makeWindowControllers
像这样:
// the proper way to insert an NSAttributedString into a textView
vc.textView.insertText(fancyString, replacementRange: NSRange(location: 0, length: 10))