如何在粘贴板中复制 NSAttributedString,允许用户粘贴或以编程方式粘贴(使用- (void)paste:(id)sender
,来自 UIResponderStandardEditActions 协议)。
I tried:
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
[pasteBoard setValue:attributedString forPasteboardType:(NSString *)kUTTypeRTF];
但这次崩溃:
-[UIPasteboard setValue:forPasteboardType:]: value is not a valid property list type'
这是可以预料的,因为 NSAttributedString 不是属性列表值。
如果用户将粘贴板的内容粘贴到我的应用程序中,我想保留属性字符串的所有标准和自定义属性。
干净的解决方案不是涉及 HTML,而是将 NSAttributedString 作为 RTF(加上纯文本后备)插入粘贴板:
- (void)setAttributedString:(NSAttributedString *)attributedString {
NSData *rtf = [attributedString dataFromRange:NSMakeRange(0, attributedString.length)
documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}
error:nil];
self.items = @[@{(id)kUTTypeRTF: [[NSString alloc] initWithData:rtf encoding:NSUTF8StringEncoding],
(id)kUTTypeUTF8PlainText: attributedString.string}];
}
Swift 5
import MobileCoreServices
public extension UIPasteboard {
func set(attributedString: NSAttributedString) {
do {
let rtf = try attributedString.data(from: NSMakeRange(0, attributedString.length), documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtf])
items = [[kUTTypeRTF as String: NSString(data: rtf, encoding: String.Encoding.utf8.rawValue)!, kUTTypeUTF8PlainText as String: attributedString.string]]
} catch {
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)