保存 UITextView
参考博文:http://www.cnblogs.com/marks007/p/4681407.html
UITextView 插入图片:
- (void)insertImage
{
CGFloatposition;
if(self.myTextView.isFirstResponder)
{
position =self.myTextView.selectedRange.location;
}
else
{
position =self.myTextView.text.length;
}
NSMutableAttributedString*attributeString = [[NSMutableAttributedStringalloc]initWithAttributedString:self.myTextView.attributedText];
NSTextAttachment*textAttachment = [[NSTextAttachmentalloc]init];
UIImage*image = [UIImageimageNamed:@"play"];
if(image.size.width>80|| image.size.height>142)
{
if(image.size.width> image.size.height)
{
intnh = image.size.height*80/image.size.width;
intnw =80;
image = [imageresizeImageWithNewSize:CGSizeMake(nw, nh)];
}
else
{
intnh =142;
intnw = image.size.width*142/image.size.height;
image = [imageresizeImageWithNewSize:CGSizeMake(nw, nh)];
}
}
textAttachment.image= image;
NSAttributedString*attrStringWithImage = [NSAttributedStringattributedStringWithAttachment:textAttachment];
[attributeStringinsertAttributedString:attrStringWithImageatIndex:position];
self.myTextView.attributedText= attributeString;
}
保存UITextView到文件中:
NSString*docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];
NSString*contentFileName = [NSStringstringWithFormat:@"content_%f.txt", [NSDatetimeIntervalSinceReferenceDate]];
NSString*contentFilePath = [docDirPathstringByAppendingPathComponent:contentFileName];
NSData*data = [self.myTextView.attributedTextdataFromRange:NSMakeRange(0,self.myTextView.attributedText.length)
documentAttributes:@{NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType}error:nil];
BOOL isWrite = [datawriteToFile:contentFilePathatomically:YES];
用的时候再取出来显示:
NSData*outputData = [[NSDataalloc]initWithContentsOfFile:contentFilePathoptions:NSDataReadingMappedIfSafeerror:nil];
NSAttributedString*temp = [[NSAttributedStringalloc]initWithData:outputData
options:@{NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType}
documentAttributes:nil
error:nil];
[self.myTextViewsetAttributedText:temp];