Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - how to copy text to clipboard?

How does one copy the contents of a Text field to the iOS clipboard?

I have the following code & want to replace the "print(..)" statement with a statement that copies the content of the text field to the iOS clipboard.

Text(self.BLEinfo.sendRcvLog)
    .onTapGesture(count: 2) {
        print("Copy text field content to ClipBoard Here..")
    }

Can't seem to find any SwiftUI examples how to do this.

Thanks!

like image 934
Gerard Avatar asked May 13 '20 10:05

Gerard


People also ask

How can I copy a text to clipboard?

Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.


2 Answers

Use the following

import MobileCoreServices // << for UTI types

// ... other code

Text(self.BLEinfo.sendRcvLog)
    .onTapGesture(count: 2) {
        UIPasteboard.general.setValue(self.BLEinfo.sendRcvLog, 
            forPasteboardType: kUTTypePlainText as String)
    }
like image 174
Asperi Avatar answered Sep 21 '22 21:09

Asperi


Text(self.BLEinfo.sendRcvLog)
    .onTapGesture(count: 2) {    
        UIPasteboard.general.string = self.BLEinfo.sendRcvLog
    }

or really fancy:

Text(self.BLEinfo.sendRcvLog)
    .contextMenu {
        Button(action: {
            UIPasteboard.general.string = self.BLEinfo.sendRcvLog
        }) {
            Text("Copy to clipboard")
            Image(systemName: "doc.on.doc")
        }
     }
like image 30
Zappel Avatar answered Sep 19 '22 21:09

Zappel