2017-06-13 34 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] 
相關問題