How it works
PasteButton is a system-provided control that reads items from the pasteboard and delivers them to your app when the person taps it. Instead of wiring up your own button and reaching into UIPasteboard or NSPasteboard directly, you declare the data types you can accept and a closure to receive them, and SwiftUI handles the rest — including hiding or disabling the control when the pasteboard holds nothing it can decode. Reach for it whenever you want a standard, privacy-respecting paste affordance that matches the platform's appearance and only activates when compatible content is available.
Declare what you accept with payloadType
The
payloadTypeparameter tellsPasteButtonwhichTransferabletype to pull off the pasteboard, and it drives whether the button is even enabled for the current clipboard contents. HerepayloadType: String.selfasks for plain text, so the button stays active only when the pasteboard carries a string.Receive the items in the action closure
The trailing closure runs when the person taps, receiving an array of decoded values of your payload type. In this example the closure parameter
stringsis the array of pasted strings, andstrings.first ?? pastedtakes the first item — falling back to the current value when the array is empty.Drive your state from the closure
Because the action is an ordinary closure, you update your view's state inside it just as you would in any button. Assigning to the
@Statepropertypastedre-renders theText(pasted)label above the button, so the pasted content appears immediately.Style it like any button
PasteButtonparticipates in SwiftUI's button styling system, so button-shaping and styling modifiers apply to it directly. The.buttonBorderShape(.capsule)modifier gives this instance a capsule outline without changing its paste behavior.
payloadType: String.self to a type the clipboard won't hold (for example a custom Transferable) and notice the PasteButton dims and ignores taps until matching content is on the pasteboard.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 PasteButtonDemo: View {
@State private var pasted = "Paste something here"
var body: some View {
VStack(spacing: 16) {
Text(pasted)
.font(.headline)
PasteButton(payloadType: String.self) { strings in
pasted = strings.first ?? pasted
}
.buttonBorderShape(.capsule)
}
.padding()
}
}