Structure

PasteButton

A system button that reads data from the pasteboard and delivers it to a closure.

Declaration 宣言

struct PasteButton

Overview 概要

Use a PasteButton when you want to provide a button for pasting data from the system pasteboard into your app. The system provides a button appearance and label appropriate to the current environment; your app can’t change this visual presentation.

You use an array of UTType instances to declare the UTIs of data types your app can handle. When the user clicks the button, your app receives the pasteboard data. You can also provide a validator closure to enable or disable the button based on the contents of the pasteboard.

In the following example, a PasteButton declares that it accepts only plaintext, using the UTF-8 text encoding. When the user clicks the button, the sample’s closure attempts to retrieve plaintext from the provided array of NSItemProvider instances. If the closure successfully loads the plaintext data, it creates a string from the data and sets it as the value of pastedText, which updates an adjoining Text view.


@State private var pastedText: String = ""
private let plainTextUTIIdentifier = UTType.utf8PlainText.identifier


var body: some View {
    HStack {
        PasteButton(
            supportedContentTypes: [.utf8PlainText]
         ) { itemProviders in
            itemProviders.first(where: {
                                    $0.hasItemConformingToTypeIdentifier(
                                        plainTextUTIIdentifier)})?
                .loadDataRepresentation(forTypeIdentifier:
                                            plainTextUTIIdentifier) { data, _ in
                    if let data = data,
                       let string = String(data: data, encoding: .utf8) {
                        pastedText = string
                    }
                }
        }
        Divider()
        Text(pastedText)
        Spacer()
    }
}

macOS window titled PasteButton Demo showing (from left to right) a button

Keep in mind that PasteButton doesn’t automatically validate and invalidate based on changes to the pasteboard. So instead of having a PasteButton as a permanent part of your UI, you should use it in transient contexts like ContextMenu.

Topics 話題

Creating a Paste Button ペースト(貼り付け)ボタンを作成する

Supporting Types 支援を行う型

Deprecated Initializers

Default Implementations 省略時実装

Relationships 関係

Conforms To 次に準拠

See Also 参照

Buttons ボタン