ios - 复制粘贴 NSAttributedString 到外部应用程序 iOS

标签 ios uipasteboard

Swift 和 iOS 新手。我试图允许用户在我的应用程序中复制 nsattributedstring 并将其粘贴到 Mail、iMessage 或他们选择的任何应用程序中。

@IBAction func action(sender: UIButton!) {

    let stringAttributes = [
        NSFontAttributeName: UIFont.boldSystemFontOfSize(14.0),
        NSBackgroundColorAttributeName: UIColor.redColor(),
    ]
    let attributedString = NSMutableAttributedString(string: "Hello world!", attributes: stringAttributes)

    do {
        let documentAttributes = [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType]
        let rtfData = try attributedString.dataFromRange(NSMakeRange(0, attributedString.length), documentAttributes: documentAttributes)
        if let rtfString = String(data: rtfData, encoding: NSUTF8StringEncoding) {
            let pb = UIPasteboard.generalPasteboard()
            return pb.string = rtfString
        }
    }
    catch {
        print("error creating RTF from Attributed String")
    }
}

粘贴后,返回:

Hello world!{ NSBackgroundColor = "UIDeviceRGBColorSpace 1 0 0 1";NSFont = " font-family:\".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 14.00pt"; }

编辑后的代码返回:

{\rtf1\ansi\anscipg1252{fontal\f0\fnil\fcharset0 .SFUIText-Semibold;}{\colortbl;\red255\green255\blue255;\red255\green0\blue0;}\pard\tx560\tx1120\tx1680...\pardirnatural\partightenfactor0 \f0\b\fs28\cf0 Hello world!

在进行研究时,我遇到了这个答案,但无法从 Leonard Pauli 的回复中得到它。也许是因为这仅在应用程序内而不是粘贴到另一个应用程序中?如果这是这个问题的重复,我很抱歉。 Paste Formatted Text, Not Images or HTML

我也无法翻译这个 Copy Text with Formatting - iOS 6 NSAttributedString to Pasteboard迅速

我可以粘贴纯文本,但不能粘贴带有任何属性的文本。

最佳答案

对于 swift 5

func copyAttributedStringToPB() {

        let stringAttributes = [
            NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14.0),
            NSAttributedString.Key.backgroundColor: UIColor.red,
        ]
        let attributedString = NSMutableAttributedString(string: "Hello world!", attributes: stringAttributes)

        do {
            let documentAttributes = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtf]
            let rtfData = try attributedString.data(from: NSMakeRange(0, attributedString.length), documentAttributes: documentAttributes)
            let pb = UIPasteboard.general
            pb.setData(rtfData, forPasteboardType: kUTTypeRTF as String)
        }
        catch {
            print("error creating RTF from Attributed String")
        }
    }

关于ios - 复制粘贴 NSAttributedString 到外部应用程序 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129975/

相关文章:

ios - 以编程方式添加的约束不起作用

ios - Firestore iOS - UITableview 中的删除功能

swift - UIPasteboard 在后台返回 nil

swift - 在 Swift/iOS 中的应用程序之间共享文件数据

ios - 基于 UIPinch 缩放图像

iphone - 拒绝后提交 iOS 二进制文件

ios - 向 UIImage 添加宽度?

swift - 如何编辑复制到 UIPasteboard 中的文本

iphone - 如何从粘贴板中获取复制的图像?

ios - 无法理解 iOS 系统 UIPasteboard