Reputation: 13
I have to copy a string along with a font and particular size. I have converted it into a NSMutableAttributedString
with all Property like font and size but can't copy it into UIPasteBoard
.
I tried to convert it into RTF data and then encoded it, but it all fails.
This is my code for the same:
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}];
Upvotes: 1
Views: 853
Reputation: 98
I had an NSAttributedString
in a Swift Playground I needed to get onto the clipboard, and I converted this code to Swift to do it. In case someone else is here for the same thing:
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]
Upvotes: 0
Reputation: 3060
Import
#import <MobileCoreServices/UTCoreTypes.h>
Copy NSAttributedString
in 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];
Paste NSAttributedString
in 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;
i hope this will help you
Upvotes: 2