weixin_43239783 2018-10-16 14:26 采纳率: 0%
浏览 336

在 learning swift书中开发Mac osx记事本应用时无法将document和text view bind起来

就是一bind就无法弹出应用窗口 按照书上 在attributed string 选择了 owner'file 但是运行显示不出来窗口
以下是document的程序 谢谢!
import Cocoa
enum NoteDocumentFileNames : String{
case TextFile = "Text.rtf"

case AttachmentsDirectory = "Attachments"

}

enum ErrorCode : Int {
case CannotAccessDocument

case CannotLoadFileWrappers

case CannotLoadText

case CannotAccessAttachments

case CannotSaveText

case CannotSaveAttachment

}

let ErrorDomain = "NotesErrorDomain"

func err(code: ErrorCode, _ userInfo:[NSObject:AnyObject]? = nil)
-> NSError{
return NSError(domain: ErrorDomain, code: code.rawValue, userInfo: userInfo as! [String : Any])
}
class Document: NSDocument {

var documentFileWrapper = FileWrapper(directoryWithFileWrappers:  [:])
var text : NSAttributedString = NSAttributedString()

override init() {
    super.init()
    // Add your subclass-specific initialization here.
}

override class var autosavesInPlace: Bool {
    return true
}

override var windowNibName: NSNib.Name? {
    // Returns the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
    return NSNib.Name("Document")
}

override func data(ofType typeName: String) throws -> Data {
    // Insert code here to write your document to data of the specified type, throwing an error in case of failure.
    // Alternatively, you could remove this method and override fileWrapper(ofType:), write(to:ofType:), or write(to:ofType:for:originalContentsURL:) instead.
    throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}

override func read(from data: Data, ofType typeName: String) throws {
    // Insert code here to read your document from the given data of the specified type, throwing an error in case of failure.
    // Alternatively, you could remove this method and override read(from:ofType:) instead.
    // If you do, you should also override isEntireFileLoaded to return false if the contents are lazily loaded.
    throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}

override func fileWrapper(ofType typeName: String) throws -> FileWrapper {
    let textRTFData = try self.text.data(
        from: NSRange(0..<self.text.length),
        documentAttributes: [
            NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtf]
    )
    if let oldTextFileWrapper = self.documentFileWrapper
        .fileWrappers?[NoteDocumentFileNames.TextFile.rawValue]{
        self.documentFileWrapper.removeFileWrapper(oldTextFileWrapper)
    }

    self.documentFileWrapper.addRegularFile(withContents: textRTFData, preferredFilename: NoteDocumentFileNames.TextFile.rawValue)

    return self.documentFileWrapper
}

override func read(from fileWrapper: FileWrapper, ofType typeName: String) throws {
    guard let fileWrappers = fileWrapper.fileWrappers else{
        throw err(code:.CannotLoadFileWrappers)
    }

    guard let documentTextData =
    fileWrappers[NoteDocumentFileNames.TextFile.rawValue]?
        .regularFileContents else {
            throw err(code:.CannotLoadText)
    }

    guard let documentText = NSAttributedString(rtf: documentTextData,
                                                documentAttributes: nil) else {
                                                    throw err(code:.CannotLoadText)
    }

    self.documentFileWrapper = fileWrapper

    self.text = documentText
}

}

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-07 07:22
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在你的文档类中,你可以使用以下方法来绑定documentViewdocumentText属性:

    class Document: NSDocument {
        
        var documentView: NSTextView!
        var documentText: NSAttributedString
        
        override init() {
            super.init()
            
            // Add your subclass-specific initialization here.
            
            documentView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 320, height: 160))
            documentView.contentSize = CGSize(width: 320, height: 160)
            documentView.scrollEnabled = true
            
            documentView.view.backgroundColor = UIColor.clear
            documentView.isScrollEnabled = true
            documentView.isZoomEnabled = true
            documentView.isAlwaysBrowsable = true
            
            documentText = NSAttributedString(string: "Your document text goes here", attributes: [.font: UIFont.systemFontOfSize(14)])
            
            documentView.documentText = documentText
            
            documentView.documentDidBeginEditing { (sender, didEndEditingReason) in
                documentText.string = sender.documentText?.string ?? ""
            }
        }
        
        override class var autosavesInPlace: Bool {
            return true
        }
        
        override var windowNibName: NSNib.Name? {
            // Returns the nib file name of the document
            // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
            return NSNib.Name("Document")
        }
        
        override func data(ofType typeName: String) throws -> Data {
            // Insert code here to write your document to data of the specified type, throwing an error in case of failure.
            // Alternatively, you could remove this method and override fileWrapper(ofType:), write(to:ofType:), or write(to:ofType:for:originalContentsURL:) instead.
            throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
        }
        
        override func read(from data: Data, ofType typeName: String) throws {
            // Insert code here to read your document from the given data of the specified type, throwing an error in case of failure.
            // Alternatively, you could remove this method and override read(from:ofType:) instead.
            // If you do, you should also override isEntireFileLoaded to return false if the contents are lazily loaded.
            throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
        }
        
        override func fileWrapper(ofType typeName: String) throws -> FileWrapper {
            let textRTFData = try self.documentText.data(
                from: NSRange(0..<self.documentText.length),
                documentAttributes: [
                    NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtf]
            )
            if let oldTextFileWrapper = self.documentFileWrapper
                .fileWrappers?[NoteDocumentFileNames.TextFile.rawValue]{
                self.documentFileWrapper.removeFileWrapper(oldTextFileWrapper)
            }
    
            self.documentFileWrapper.addRegularFile(withContents: textRTFData, preferredFilename: NoteDocumentFileNames.TextFile.rawValue)
    
            return self.documentFileWrapper
        }
        
        override func read(from fileWrapper: FileWrapper, ofType typeName: String) throws {
            guard let fileWrappers = fileWrapper.fileWrappers else{
                throw err(code:.CannotLoadFileWrappers)
            }
    
            guard let documentTextData =
                fileWrappers[NoteDocumentFileNames.TextFile.rawValue]?
                    .regularFileContents else {
                        throw err(code:.CannotLoadText)
            }
    
            guard let documentText = NSAttributedString(rtf: documentTextData,
                                                        documentAttributes: nil) else {
                                    throw err(code:.CannotLoadText)
            }
    
            self.documentFileWrapper = fileWrapper
    
            self.documentText = documentText
        }
    }
    

    这样,你就可以将documentViewdocumentText进行绑定,并且可以在documentView被加载后更新documentText

    评论

报告相同问题?