美文网首页
保存 UITextView

保存 UITextView

作者: BADTZMARU_ye | 来源:发表于2017-05-11 16:38 被阅读0次

    参考博文: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];

    相关文章

      网友评论

          本文标题:保存 UITextView

          本文链接:https://www.haomeiwen.com/subject/eynotxtx.html