Search code examples
swiftuicopy-paste

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!


Solution

  • Use the following - put shown text into pasteboard for specific type (and you can set as many values and types as needed)

    Update: for Xcode 13+, because of "'kUTTypePlainText' was deprecated in iOS 15.0..." warning

    import UniformTypeIdentifiers
    
    Text(self.BLEinfo.sendRcvLog)
        .onTapGesture(count: 2) {
            UIPasteboard.general.setValue(self.BLEinfo.sendRcvLog,
                forPasteboardType: UTType.plainText.identifier)
        }
    

    for older versions:

    import MobileCoreServices // << for UTI types
    
    // ... other code
    
    Text(self.BLEinfo.sendRcvLog)
        .onTapGesture(count: 2) {
            UIPasteboard.general.setValue(self.BLEinfo.sendRcvLog, 
                forPasteboardType: kUTTypePlainText as String)
        }