Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active July 5, 2024 18:05
Show Gist options
  • Save theoknock/7ea1d9f7aeaf234235d6ab508b45065b to your computer and use it in GitHub Desktop.
Save theoknock/7ea1d9f7aeaf234235d6ab508b45065b to your computer and use it in GitHub Desktop.
FileDocument
import SwiftUI
struct ContentView: View {
@Binding var document: TextFile
var body: some View {
HStack {
TextEditor(text: $document.text)
}
}
}
import SwiftUI
import UniformTypeIdentifiers
struct TextFile: FileDocument {
static var readableContentTypes: [UTType] { [.plainText] }
var text = ""
init(initialText: String = "") {
text = initialText
}
init(configuration: ReadConfiguration) throws {
if let data = configuration.file.regularFileContents {
text = String(decoding: data, as: UTF8.self)
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = Data(text.utf8)
return FileWrapper(regularFileWithContents: data)
}
}
@main
struct MyApp: App {
var body: some Scene {
DocumentGroup(newDocument: TextFile()) { file in
ContentView(document: file.$document)
}
}
}
struct MyApp_Previews: PreviewProvider {
static var previews: some View {
ContentView(document: .constant(TextFile()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment