美文网首页iOS
UITextView之textStorage属性介绍

UITextView之textStorage属性介绍

作者: ys简单0 | 来源:发表于2017-02-13 13:55 被阅读312次

    在聊天过程中很多时候都想要发送本界面的一张图片或者是一个表情,或者是一张相册中照片直接显示在文本框中发送出去,接下来就简单介绍一下通过UITextViewtextStorage属性来实现这个问题;textStorage其实是一个装载内容的容器,其里面保存的东西决定了textview的富文本显示方式.

    点入UITextView的KPI中找到textStorage,大家可以看到@property(nonatomic,readonly,strong) NSTextStorage *textStorage NS_AVAILABLE_IOS(7_0);再点进入NSTextStorage可以看到NS_CLASS_AVAILABLE(10_0, 7_0) @interface NSTextStorage : NSMutableAttributedString看到这里我们知道其实这个属性是继承自NSMutableAttributedString我们也就不奇怪为什么其里面的内容可以决定textview的富文本排列方式;接下来看一下实现方式:
    viewDidLoad中简单的创建一个textview和一张图片,我们实现点击图片,让其显示在textview中

    - (void)viewDidLoad {
        [super viewDidLoad];
        UIImageView *imgeview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"123.jpg"]];
        imgeview.frame = CGRectMake(100, 10, 50, 50);
        [self.view addSubview:imgeview];
        imgeview.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectImageTosend:)];
        [imgeview addGestureRecognizer:tap];
        
        self.textview = [[UITextView alloc]initWithFrame:CGRectMake(10, 80, 200, 80)];
        _textview.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:_textview];
    }
    

    在imageview的tap手势方法中实现

    -(void)selectImageTosend:(UITapGestureRecognizer *)tap{
        UIImageView *imageview = (UIImageView *)tap.view;
        NSTextAttachment *atacchment = [[NSTextAttachment alloc]init];
        atacchment.image = imageview.image;
        //图片在textview中显示的大小
        atacchment.bounds = CGRectMake(0, 0, 20, 20);
        NSAttributedString *attributedStr = [[NSAttributedString alloc]initWithString:@""];
        attributedStr = [NSAttributedString attributedStringWithAttachment:atacchment];
        //textStorage装载内容的容器,继承自NSMutableAttributedString,其里面保存的东西决定了textview的富文本显示方式
        [self.textview.textStorage appendAttributedString:attributedStr];
    }
    

    当然经过优化就可以实现像iphone发送短信时发送照片显示在输入框中一样
    效果如下:

    IMG_0127.PNG

    相关文章

      网友评论

        本文标题:UITextView之textStorage属性介绍

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