Last active
July 5, 2024 18:05
-
-
Save theoknock/7ea1d9f7aeaf234235d6ab508b45065b to your computer and use it in GitHub Desktop.
FileDocument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@Binding var document: TextFile | |
var body: some View { | |
HStack { | |
TextEditor(text: $document.text) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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