How it works
NewDocumentButton is a control that creates and opens a new document in a document-based app. It encapsulates the entire "new document" action, so you don't have to wire up your own button to a newDocument action or manage the document scene yourself — you give it a label and a closure that produces the initial document value, and SwiftUI handles opening a fresh scene for it. Reach for it anywhere you'd otherwise hand-build a button whose job is to spawn a new document, such as a toolbar, a menu, or an empty-state prompt.
Construct it with a title and a document-producing closure
The initializer takes a label (here the string literal
"New Drawing") and a trailing closure that returns the new document instance. Each time the button is activated, SwiftUI calls that closure —{ Drawing() }— to mint a fresh document value and open it in a new scene, so the closure is your hook for the document's initial state.Supply a label
The convenience initializer used here accepts a string for the button's text, exactly like
Button.NewDocumentButton("New Drawing")renders "New Drawing" as the title; other initializers let you provide a custom label view when you need an icon or styled content instead of plain text.Return the document type from the closure
The closure's return type must match the document type your app's
DocumentGroupdeclares. In the example the closure returnsDrawing(), so this button is bound to scenes that editDrawingdocuments; SwiftUI infers the document type from what the closure produces.Style it like any button
NewDocumentButtonparticipates in the standard button styling system, so button modifiers apply directly to it. Here.buttonStyle(.borderedProminent)gives it a filled, prominent appearance — you can swap in anyButtonStyleor restyle it to fit a toolbar or sidebar just as you would aButton.Place it where a new-document action belongs
Drop the control into whatever container hosts the action — it sits inside the surrounding
VStacknext to the descriptiveTextviews here. Because it carries its own behavior, no@Environmentaction or binding is needed at the call site; the button is self-contained wherever you put it.
.buttonStyle(.borderedProminent) to .buttonStyle(.bordered) to see NewDocumentButton adopt a lighter, outlined appearance while keeping the same new-document behavior.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct NewDocumentButtonDemo: View {
var body: some View {
VStack(spacing: 16) {
Text("Document Actions")
.font(.headline)
NewDocumentButton("New Drawing") {
Drawing()
}
.buttonStyle(.borderedProminent)
Text("Creates a new document scene")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding()
}
}