Copy NSAttributedString in UIPasteBoard

前端 未结 4 1365
故里飘歌
故里飘歌 2020-11-30 09:15

How do you copy an NSAttributedString in the pasteboard, to allow the user to paste, or to paste programmatically (with - (void)paste:(id)sender

4条回答
  •  再見小時候
    2020-11-30 09:38

    It is quite simple:

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

提交回复
热议问题