iOS中的图文混排

废话不多说,直接上图:

iOS中的图文混排_第1张图片

图文混排实现代码:

// 初始化可插入图片的字符串
        NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] init];
        // 拼接之前的字符(否则会覆盖掉前面输入的字符)
        [attributeStr appendAttributedString:self.attributedText];
        
        // 加载图片,EmotionAttachment是我自定义的类,继承自NSTextAttachment.
        EmotionAttachment *attach = [[EmotionAttachment alloc] init];
        attach.emotion = emotion;
        
        CGFloat imageHY = self.font.lineHeight;
        // 设置图片居中
        attach.bounds = CGRectMake(0, -4, imageHY, imageHY);
        NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attach];
        // 获取光标位置
        NSUInteger loc = self.selectedRange.location;
        //[attributeStr appendAttributedString:imageStr];
        // 插入图片到光标所在位置
        [attributeStr insertAttributedString:imageStr atIndex:loc];
        
        [attributeStr addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0,attributeStr.length)];
        self.attributedText = attributeStr;
        // 移动光标到插入的图片后面
        self.selectedRange = NSMakeRange(loc + 1, 0);

 

 

 

转载于:https://www.cnblogs.com/zwois/p/4635177.html

你可能感兴趣的:(iOS中的图文混排)