将带有字体和大小的 NSMutableAttributedString 放入 UIPasteboard 以粘贴到另一个应用程序

Putting NSMutableAttributedString with font and size into UIPasteboard to paste into another app

我必须复制一个字符串以及字体和特定大小。我已将其转换为 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}];

导入

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

希望对您有所帮助

我在 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]