iOS开发 - UITextView的图文混排

实现步骤:

  • 生成一个图片的附件
  • 创建一个富文本对象
  • 设置图片的bounds
  • 将图片添加到富文本上
  • 把图片富文本转换成可变的富文本

图片文本

  1. 创建NSTextAttachment的对象,用来装载图片
  2. NSTextAttachment对象的image属性设置为想要使用的图片
  3. 设置NSTextAttachment对象bounds大小,也就是要显示的图片的大小
  4. [NSAttributedString attributedStringWithAttachment:attch]方法,将图片添加到富文本上


例子:

//1. 生成一个图片的附件

            UIImage *image1 = [UIImage imageWithContentsOfFile:path];

   ///根据自己项目的到真实的宽高         

             NSArray *widths = [temp3[1] componentsSeparatedByString:@"<HEIGHT>"];

              NSArray *heights = [widths[1] componentsSeparatedByString:@"<ID>"];

            CGFloat realWidth = [widths[0] floatValue];

            CGFloat realHeight = [heights[0] floatValue];

///

            //2.创建一个富文本对象,用来装载图片

            NSTextAttachment *attachment = [[NSTextAttachment alloc] init];

            //给附件添加图片

            attachment.image = image1;

            

            CGFloat imgWidth = [self getImgWidthWithImg:realWidth realheight:realHeight];

            CGFloat imgHeight = [self getImgHeightWithImg:realWidth realheight:realHeight];

            //3.设置图片的bounds :调整一下图片的位置,如果你的图片偏上或者偏下,调整一下bounds的y值即可

            attachment.bounds = CGRectMake(0, 0, imgWidth, imgHeight);

            

             //3.将图片添加到富文本上

            NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

            //4.把图片富文本转换成可变的富文本

            NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithAttributedString:_cardContentTv.attributedText];

            

            

            [string insertAttributedString:textAttachmentString atIndex:_cardContentTv.selectedRange.location];

            

_cardContentTv.attributedText = string;




遇到的问题:

当图片存在沙盒documents中时,每次重启APP沙盒docu路径是变化的,所以要使用之前保存在沙盒中的图片的时候要用当前的沙盒doc路径




别人写的一个基于swift的demo   https://github.com/VitasLiu/WeiBoComposeDemo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值