gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:38:56 30 4
gpt4 key购买 nike

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com