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")
}
}
Run Code Online (Sandbox Code Playgroud)
粘贴后,将返回:
你好世界!{ NSBackgroundColor = "UIDeviceRGBColorSpace 1 0 0 1";NSFont = " font-family:\".SFUIText-Semibold\"; 字体粗细:粗体;字体样式:正常;字体大小: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 世界你好!
在进行研究时,我遇到了这个答案,但无法从伦纳德·泡利的回应中得到它。也许是因为这仅在应用程序内而不是粘贴到另一个应用程序中?如果这是这个问题的重复,我很抱歉。 粘贴格式化文本,而不是图像或 HTML
我也无法将此Copy Text with Formatting - iOS 6 NSAttributedString to Pasteboard翻译为 swift
我可以粘贴纯文本,但不能粘贴具有任何属性的文本。
我已经更新了您的代码以将您正在创建的 RTF 数据正确保存到粘贴板,但是,加载 RTF 数据并将其放回对象中NSAttributedString似乎是一项手动任务。
因此,复制和粘贴行为仅在开发人员明确支持以这种方式复制和粘贴 RTF 数据的上下文中起作用。
不幸的是,在我测试代码的 Playgrounds 中,Pasteboard 的字符串属性被设置为包含 RTF 数据的纯文本版本(其中充满了标记和奇怪的控制字符)。我无法找到解决此问题的解决方案,这意味着不以这种方式支持 RTF 的应用程序可能仍会粘贴标记的 RTF 纯文本,而不是属性文本...:(
这将帮助您实现一些目标(在应用程序中复制粘贴 RTF),但显然不是很好。我的项目也依赖于这种行为,所以如果有人有其他想法,我也很想知道。
import MobileCoreServices
// ----- Copy ------
func copyAttributedStringToPB() {
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)
let pb = UIPasteboard.generalPasteboard()
pb.setData(rtfData, forPasteboardType: kUTTypeRTF as String)
}
catch {
print("error creating RTF from Attributed String")
}
}
// -------- Paste -------
let pb = UIPasteboard.generalPasteboard()
let data = pb.dataForPasteboardType(kUTTypeRTF as String)
let pastedAttributedString = try! NSAttributedString(data: data!, options: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType], documentAttributes: nil)
Run Code Online (Sandbox Code Playgroud)