跳转至
Structure

DocumentGroup

A scene that enables support for opening, creating, and saving documents.

Declaration

struct DocumentGroup<Document, Content> : Scene where Content : View

Overview

DocumentGroup provides a default scene for basic file management.

import SwiftUI
import UniformTypeIdentifiers

@main
struct ExampleApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: TextFile()) { file in
            ExampleView(document: file.$document)
        }
    }
}

struct ExampleView: View {
    @Binding var document: TextFile

    var body: some View {
        TextEditor(text: $document.text)
    }
}

struct TextFile: FileDocument {
    // Support only plain text
    static var readableContentTypes = [UTType.plainText]

    // Create an empty document
    var text = ""

    // Create a document
    init(initialText: String = "") {
        text = initialText
    }

    // Loads data has been saved previously. See the ReadConfiguration documentation for more
    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents,
            let string = String(data: data, encoding: .utf8)
        else {
            throw CocoaError(.fileReadCorruptFile)
        }
        text = string
    }

    // The saving function
    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        let data = text.data(using: .utf8)!
        return .init(regularFileWithContents: data)
    }
}
Document Group

Availability

iOS 14.0+

macOS 11.0+

Topics


Type Alias

Body The type of scene that represents the body of this scene.


Initializer

init(newDocument:editor:) Creates a document group that is able to create and edit reference file documents.

init(newDocument:editor:) Creates a document group that is able to create and edit file documents.

init(viewing:viewer:) Creates a document group that is able to view file documents.

init(viewing:viewer:) Creates a document group that is able to view reference file documents.


Instance Property

body The content and behavior of the scene.