2017-06-13 35 views
0

我必须复制一个字符串以及字体和特定大小。我已将其转换为NSMutableAttributedString,其中包含字体和大小等所有Property,但无法将其复制到UIPasteBoard将带有字体和大小的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

进口

#import <MobileCoreServices/UTCoreTypes.h> 

复制NSAttributedString在IOS

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]; 

粘贴NSAttributedString在IOS

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; 

我希望这将帮助你

+0

检查现在这个样子, – Dhiru

+0

在NSDictionary中要将两个对象..一个是RTF等是字符串..和uipasteboard使用字符串.. –

+0

是的,rtf是字体 – Dhiru

0

我在斯威夫特游乐场我需要得到到剪贴板上有一个NSAttributedString,我转换这个代码斯威夫特做到这一点。如果别人在这里同样的事情:

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] 
相关问题