Copy Text to Clipboard in SwiftUI


In this tutorial, you are going to learn how to copy text to the clipboard in SwiftUI with the help of examples.

To copy a string or text, we can use the UIPasteboard class. UIPasteboard can help us to share data from one place to another within our app.

You have to create an object of this class and then need to use the generalPasteboard() method from this class:

private let pastboard = UIPasteboard.general

Now if we want to copy a text or string to the clipboard by clicking a button, then below is how we can do it:

        Button {
            pastboard.string = "This Text Copied to Clipboard"
        } label: {
            Label("Copy to Clipboard", systemImage: "doc.on.doc")
        }

Copy Text from a SwiftUI TextField to clipboard

Now suppose, you have a SwiftUI TextField and you enter some text in it. Now you want to copy the text from that TextField in SwiftUI. You can perform this task easily using UIPasteboard. Below is the given code for this:

    @State var myText: String = ""
    private let pastboard = UIPasteboard.general
    
    var body: some View {
        
        
        TextField("This is plceholdr", text: $myText)
            .border(.red).padding()
        
        
        Button {
            pastboard.string = myText
        } label: {
            Label("Copy to Clipboard", systemImage: "doc.on.doc")
        }
           
        
    }

In the above program, we bind the state variable myText to the text field. In the button action, we are storing the state variable of the text field to the pastboard.string.

Now when we type some text in the TextField and then tap on the Copy to Clipboard button, it is copying our text from the text field.