'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 1:[1]
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)
}
Solution 2:[2]
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")
}
}
Solution 3:[3]
For iOS 14+
UIPasteboard.general.setValue(message, forPasteboardType: "public.plain-text")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Zappel |
Solution 3 | Chat Dp |