高级目标 :。
我正在尝试制作一个可以预览降价文件的文本编辑器。
当前状态:
读/写文本文件效果很好。
问题:
很难在textView中添加/替换NSAttributedString。
这是我的代码: 进口可可 import Down // md转换lib
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()
中创建的textview替换该textView,但这似乎不起作用。
我希望在新窗口中看到It might be working...
,但只会看到一个空白的textView。
有什么想法吗?
更新和解决方案
感谢@Willeke提出了这个问题。我假设首先调用makeWindowControllers()
。原来,read()
被调用,然后makeWindowControllers()
被调用。
因此,我可以将var fancyString:NSAttributedString = NSAttributedString(string: "hello")
分配为类变量。然后从fancyString
中的文件内容中设置read()
,然后像这样更新makeWindowControllers
中的textView:
// the proper way to insert an NSAttributedString into a textView
vc.textView.insertText(fancyString, replacementRange: NSRange(location: 0, length: 10))
答案 0 :(得分:1)
makeWindowControllers
之后调用 read(from data: Data, ofType typeName: String)
。将属性字符串分配给Document
属性,然后将文本添加到makeWindowControllers
的文本视图中。
详细信息:Message Flow in the Document Architecture, Opening a Document中的Document-Based App Programming Guide for Mac