swiftuipasteboard

How do you copy text from a text view with a different font and when pasted on other apps like messages, it's the same font?


This line to just copy the text itself without font and paste it works:

pasteBoard.string = MainController.customTextView.text 

I've tried looking at similar answers that people asked about this question but almost every answer I see is in Objective C and outdated. By looking at other answers like this I think I got the copy working but when I paste the copied text, it doesn't paste anything. Here's what I have for my copy function:

    @objc func handleCopyButton() {
    MainController.customTextView.resignFirstResponder() // dismiss keyboard

    // Setup code in overridden UITextView.copy/paste
    let selectedRange = MainController.customTextView.selectedRange
    let selectedText = MainController.customTextView.attributedText.attributedSubstring(from: selectedRange)

    // UTI List
    let utf8StringType = "public.utf8-plain-text"
    let rtfdStringType = "com.apple.flat-rtfd"

    // Try custom copy
    do {
        // Convert attributedString to rtfd data
        let fullRange = NSRange(location: 0, length: selectedText.string.count)
        let data:NSData? = try selectedText.data(from: fullRange, documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtfd]) as NSData

        if let data = data {

            // Set pasteboard values (rtfd and plain text fallback)
            pasteBoard.items = [[rtfdStringType: data], [utf8StringType: selectedText.string]]

        }
    } catch { print("Couldn't copy") }

    // Copy if custom copy not available
    MainController.customTextView.copy()
}

Let me know if you have any questions on this. Thank you in advance!

Edit: For what I was trying to do, it turns out you can't copy and paste fonts (at least on iOS but in MacOS I believe you can), but what you could do is copy and paste unicode characters that looks like different fonts. Check this solution out if it's something you're interested in.


Solution