图文混排

-(void)insetEmotion:(EmotionModel*)emotionModel{
    if(emotionModel.code){
        /**
         在TextView中插入图片首选要知道光标的位置 比如在一段文字中间 或着 一段文字末尾
         
         */
        //self.statusTextView.text = emotionModel.chs;
        /**
         这个方法会自动将传入的参数插入到光标的位置
         现在插入的是对应的文字信息 以后会把这个信息发送给新浪
         现在要将文字信息以图片显示在文本框中
         emoji就是字符串 这样可以直接插入到 文本框中
         */
        [self insertText:emotionModel.code.emoji];
        
    }else if(emotionModel.png){
        /**
         如果是png (默认和浪小花)就需要将相应的图片信息加载进来
         如果要图文混排就需要用到AttributedString和NSMutableAttributededString
         
         statusTextView 有两个属性可以设置文本
         self.statusTextView.attributedText
         self.statusTextView.text
         */
        //[self.statusTextView insertText:emotionModel.png];
        //如果这样写当 用户选择 默认或浪小花图片时 就会创造一个空的attributedText 将之前的文字覆盖
        
        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]init];
        /**下面这句是错误的 如果之前普通文字中包含图片信息 self.statusTextView.text 拿不到*/
        //[attributedText appendAttributedString:self.statusTextView.text];
        //拼接之前的文字 图片和普通文字
        [attributedText appendAttributedString:self.attributedText];
        //直接将attributedText给statusTextView 那么以前设置的文字都没有了所以attributedText要拼接之前的文本框中的文字
        self.attributedText = attributedText;
        
        UIImage *image = [UIImage imageNamed:emotionModel.png];
        
        NSTextAttachment *attch = [[NSTextAttachment alloc]init];
        attch.image = image;
        CGFloat WHImage = self.font.lineHeight;
        attch.bounds = CGRectMake(0, -4, WHImage, WHImage);
        /** 将一个附件转化为一个字符串*/
        NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attch];
        /** 这个方法只能将图片加入到字符串的结尾*/
        //[attributedText appendAttributedString:imageStr];
        [attributedText insertAttributedString:imageStr atIndex:self.selectedRange.location];
        NSInteger loc = self.selectedRange.location;
        
        //self.statusTextView.selectedRange.location+1;
        // self.textView.font 只能对self.statusTextView.text 这里面的文字进行设置 对带有附件的文字 attrubutedText无效
        
        //设置attributedText文字字体
        [attributedText addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedText.length)];
        //最后将带有附件的字符串 赋值给文本框
        self.attributedText = attributedText;
        
        //设置完文字移动光标
        self.selectedRange = NSMakeRange(loc+1, 0);
        /**
         selectedRange 本来是用来控制文字的选中范围
         如果selectedRange.length为0相当于是用来控制输入框的光标位置selectedRange.location就是输入框的光标位置
         */
    }


}