Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Opening a New Tab with Text in a Document-Based App

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)
            }
        }
    }
}
Answered by DTS Engineer in 837263022

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.

Accepted Answer

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.

Thank you, DTS Engineer. It works. I forgot that I had had the newDocument environment thing 4 days earlier. I'm too old for new things. I didn't know about the tab-opening preference under Desktop & Dock.

Opening a New Tab with Text in a Document-Based App
 
 
Q