Copy NSAttributedString in UIPasteBoard

前端 未结 4 1368
故里飘歌
故里飘歌 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:56

    @Guillaume's approach using HTML doesn't work for me (at least in iOS 7.1 beta 5).

    The cleaner solution is to insert NSAttributedStrings as RTF (plus plaintext fallback) into the paste board:

    - (void)setAttributedString:(NSAttributedString *)attributedString {
        NSData *rtf = [attributedString dataFromRange:NSMakeRange(0, attributedString.length)
                                   documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}
                                                error:nil];
        self.items = @[@{(id)kUTTypeRTF: [[NSString alloc] initWithData:rtf encoding:NSUTF8StringEncoding],
                         (id)kUTTypeUTF8PlainText: attributedString.string}];
    }
    

    Swift 2.3

    public extension UIPasteboard {
      public func set(attributedString: NSAttributedString?) {
    
        guard let attributedString = attributedString else {
          return
        }
    
        do {
          let rtf = try attributedString.dataFromRange(NSMakeRange(0, attributedString.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType])
          items = [[kUTTypeRTF as String: NSString(data: rtf, encoding: NSUTF8StringEncoding)!, kUTTypeUTF8PlainText as String: attributedString.string]]
    
        } catch {
    
        }
      }
    }
    

    Swift 3

    import MobileCoreServices
    public extension UIPasteboard {
      public func set(attributedString: NSAttributedString?) {
    
        guard let attributedString = attributedString else {
          return
        }
    
        do {
          let rtf = try attributedString.data(from: NSMakeRange(0, attributedString.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType])
          items = [[kUTTypeRTF as String: NSString(data: rtf, encoding: String.Encoding.utf8.rawValue)!, kUTTypeUTF8PlainText as String: attributedString.string]]
    
        } catch {
    
        }
      }
    }
    

提交回复
热议问题