我必须复制字符串以及字体和特定大小。我已将其转换为NSMutableAttributedString
,其中所有属性均为字体和大小,但无法将其复制到UIPasteBoard
。
我尝试将其转换为RTF数据然后对其进行编码,但都失败了。
这是我的相同代码:
NSRange attRange = NSMakeRange(0, [textString length]);
attString = [[NSMutableAttributedString alloc]initWithString:textString];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:[fontsArray objectAtIndex:index] size:12] range:attRange];
NSData *data = [attString dataFromRange:NSMakeRange(0, [attString length]) documentAttributes:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} error:nil];
UIPasteboard *paste = [UIPasteboard generalPasteboard];
paste.items = @[@{(id)kUTTypeRTFD: [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding],(id)kUTTypeUTF8PlainText: attString.string}];
答案 0 :(得分:1)
导入
#import <MobileCoreServices/UTCoreTypes.h>
在ios中 复制 NSAttributedString
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
NSData *rtf = [attributedString dataFromRange:NSMakeRange(0, attributedString.length)
documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType}
error:nil];
if (rtf) {
[item setObject:rtf forKey:(id)kUTTypeFlatRTFD];
}
[item setObject:attributedString.string forKey:(id)kUTTypeUTF8PlainText];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.items = @[item];
在ios中 粘贴 NSAttributedString
NSAttributedString *attributedString;
NSData* rtfData = [[UIPasteboard generalPasteboard] dataForPasteboardType:(id)kUTTypeFlatRTFD];
if (rtfData) {
attributedString = [[NSAttributedString alloc] initWithData:rtfData options:@{NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
}
_lblResult.attributedText=attributedString;
我希望这会对你有所帮助
答案 1 :(得分:0)
我在Swift Playground中有一个NSAttributedString
我需要进入剪贴板,然后我将此代码转换为Swift来完成它。万一其他人在这里做同样的事情:
import MobileCoreServices // defines the UTType constants
// UIPasteboard expects Dictionary<String,Any>, so either use
// explicit type in the definition or downcast it like I have.
var item = [kUTTypeUTF8PlainText as String : attributedString.string as Any]
if let rtf = try? attributedString.data(from: NSMakeRange(0,
attributedString.length), documentAttributes:
[NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType]) {
// The UTType constants are CFStrings that have to be
// downcast explicitly to String (which is one reason I
// defined item with a downcast in the first place)
item[kUTTypeFlatRTFD as String] = rtf
}
UIPasteboard.general.items = [item]