SwiftUI - how to copy text to clipboard?
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)
}
For iOS 14+
UIPasteboard.general.setValue(message, forPasteboardType: "public.plain-text")
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")
}
}