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 …