How to add a copy button in Xcode

I would like to now how to make a button that copy a text.

Exemple : When I touch this button the text/link apple.com will be copied. The user can now paste the text/link in safari.

Accepted Reply

Here is how to copy a text in pasteBoard.

This is for macOS app, but easily adapted to iOS:

You have a copy button

                Button(action: {
                    copyToClipboard()
                }) {
                    Text("\(buttonText)")  
                        .font(.system(size: 12))
                }

You declare a pasteBoard

    private let pasteboard = NSPasteboard.general

The text to copy is in a Sate var or in a computed var

    var fullText : String {
        var text = ""
        // build the text as needed
        return text
    }

And a copy func:

    func copyToClipboard() {
        
        pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
        pasteboard.setString(fullText, forType: .string)
        
        self.buttonText = "Copied!"
    }

Replies

Here is how to copy a text in pasteBoard.

This is for macOS app, but easily adapted to iOS:

You have a copy button

                Button(action: {
                    copyToClipboard()
                }) {
                    Text("\(buttonText)")  
                        .font(.system(size: 12))
                }

You declare a pasteBoard

    private let pasteboard = NSPasteboard.general

The text to copy is in a Sate var or in a computed var

    var fullText : String {
        var text = ""
        // build the text as needed
        return text
    }

And a copy func:

    func copyToClipboard() {
        
        pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
        pasteboard.setString(fullText, forType: .string)
        
        self.buttonText = "Copied!"
    }

Tanks it work