I have a sample document-based application for macOS. According to this article (https://jujodi.medium.com/adding-a-new-tab-keyboard-shortcut-to-a-swiftui-macos-application-56b5f389d2e6), you can create a new tab programmatically. It works. Now, my question is whether you can open a tab with some data. Is that possible under the SwiftUI framework? I could do it in Cocoa. Hopefully, we can do it in SwiftUI as well. Muchos thankos.
import SwiftUI
@main
struct SomeApp: App {
var body: some Scene {
DocumentGroup(newDocument: SomeDocument()) { file in
ContentView(document: file.$document)
}
}
}
import SwiftUI
struct ContentView: View {
@Binding var document: SomeDocument
var body: some View {
VStack {
TextEditor(text: $document.text)
Button {
createNewTab()
} label: {
Text("New tab")
.frame(width: 64)
}
}
}
}
extension ContentView {
private func createNewTab() {
if let currentWindow = NSApp.keyWindow,
let windowController = currentWindow.windowController {
windowController.newWindowForTab(nil)
if let newWindow = NSApp.keyWindow,
currentWindow != newWindow {
currentWindow.addTabbedWindow(newWindow, ordered: .above)
}
}
}
}
In a document-based app, you can open a new document using newDocument
environment key. For example:
struct NewDocumentFromSelection: View {
@FocusedBinding(\.selectedText) private var selectedText: String?
@Environment(\.newDocument) private var newDocument
var body: some View {
Button("New Document With Selection") {
newDocument(TextDocument(text: selectedText))
}
}
}
Keep in mind that, windows will open in a tab if that is set to "always" in the user preferences, otherwise it will be a separate window.