iOS富文本图文混排(NSMutableAttributedString分类实现)

说明:旨在减少对第三方的依赖,一个比较简单的实现思路;比起像YYLabel等强大的框架只是冰山一角!重在学习☺️☺️(swift和objectC都有提供哦)

废话不都说直接上代码 (git的demo,点击下载

我就写一下swift的具体代码,OC的就不啰嗦啦

在控制器的实现代码,很随意

//
//  ViewController.swift
//  KVAttributedString
//
//  Created by 李康卫 on 16/11/8.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置UI
        setupUI()
//        testLabel.attributedText = NSMutableAttributedString.init(imageName: "compose_mentionbutton_background_highlighted", contentString: "helloMISSBodyMeimi", attributedInsertType: KVAttributedInsertType.First, label: testLabel)
//        testLabel.attributedText = NSMutableAttributedString.init(content: "还是短发hi阿萨[微笑]防守打法看见就看发的啥看法", color: UIColor.redColor(), colorString: "见就看发的")
        let nsStr =  "还是短发hi阿萨[微笑]防守打法看见就看发的啥看法还是短发hi阿萨[微笑]防守打法看见就看发的啥看法还是短发hi阿萨[微笑]防守打法看见就看发的啥看法" as NSString
        testLabel.attributedText = nsStr.emojiAttributedString()
    }
    //布局label
    private func setupUI() {
        self.view.addSubview(testLabel)
        
        testLabel.translatesAutoresizingMaskIntoConstraints = false
        
        self.view.addConstraint(NSLayoutConstraint(item: testLabel, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant:50))
        self.view.addConstraint(NSLayoutConstraint(item: testLabel, attribute: NSLayoutAttribute.Leading, relatedBy: .Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 50))
        self.view.addConstraint(NSLayoutConstraint(item: testLabel, attribute: NSLayoutAttribute.Trailing, relatedBy: .Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -50))
    }

    //懒加载
    private lazy var testLabel: UILabel = {
        let label = UILabel()
        label.text = "holleWrod"
        label.textColor = UIColor.cyanColor()
        label.numberOfLines = 0
        return label;
    }()
}

每种方法对应的效果如图所示
convenience init(imageName: String,contentString: String ,attributedInsertType: (KVAttributedInsertType),label: UILabel)


593027BF-5D58-4C80-987F-591A86E22E3A.png

BE006998-D85F-49EB-B50A-D9685EECE58A.png

convenience init(content: String,color: UIColor,colorString: String)


7CFB5F48-1107-4DCE-98C0-3E87D5A93618.png

func emojiAttributedString() ->NSMutableAttributedString


375358A0-8D90-4FC4-AA57-F14C0327B2D6.png

核心代码:

import UIKit

public enum KVAttributedInsertType : Int {
    
    case First
    case last
}

extension NSMutableAttributedString {
    ///文本前后插入图片
    convenience init(imageName: String,contentString: String ,attributedInsertType: (KVAttributedInsertType),label: UILabel){
        self.init()
        let att = NSAttributedString(string: contentString)
        self.appendAttributedString(att)
        //根据附件生成富文本
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named:imageName)
//        //设置(图片)字体大小
        let attachmentH = label.font.lineHeight
        //调节图片的大小
        attachment.bounds = CGRectMake(0, -3, 25, attachmentH)
        let attString = NSAttributedString(attachment: attachment)
        if attributedInsertType == .First {
            self.insertAttributedString(attString, atIndex: 0)
        } else {
            self.insertAttributedString(attString, atIndex: (contentString as NSString).length)
        }
        
    }
    ///根据文字内容修改指定的文字的颜色
    convenience init(content: String,color: UIColor,colorString: String) {
        self.init()
        let contentAttStr = NSMutableAttributedString(string: content);
        let range: NSRange = (content as NSString).rangeOfString(colorString)
        contentAttStr.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
        self.appendAttributedString(contentAttStr)
    }
    
}

extension NSString {
     func emojiAttributedString() ->NSMutableAttributedString {
        
        let plistArr = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("emoticon.plist", ofType: nil)!)
        
        //可变的属性文本
        let attContent = NSMutableAttributedString(string: self as String)
        
        //  1.通过正则表达式取出表情图片的名称\[\w+?\]
        let pattern = "\\[\\w+?\\]"
        //        let error = NSError.init();
        print("pattern\(pattern)")
        //抛出的异常处理
        var regx = NSRegularExpression()
        do {
            regx = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.init(rawValue: 0))
        } catch let error as NSError {
            print(error)
            return attContent
        }
        
        // 获的匹配结果
        //        __block NSString *emoticonName;
        let results = regx.matchesInString(self as String, options: NSMatchingOptions.init(rawValue: 0), range: NSMakeRange(0, (self as NSString).length))
        for result in results {
            let resultStr = self.substringWithRange(result.range)
            plistArr?.enumerateObjectsUsingBlock({ (obj, idx, __) in
                let desStr = obj["des"] as! String
                if desStr == resultStr {
                    let emotionName = (obj["name"])!
                    //必须要注意强拆,需要多打印调试
                    print("\(emotionName!)@2x.gif")
                    let attachment = NSTextAttachment();
                    //设置(图片)字体大小根据需要作调整
                    attachment.bounds = CGRectMake(0, -3, 25, 25)
                    attachment.image = UIImage(named: "\(emotionName!)@2x.gif")
                
                    let emojiStr = NSAttributedString(attachment: attachment)
                    attContent .replaceCharactersInRange(result.range, withAttributedString: emojiStr)
                }
            })
        }
        return attContent
    }
}

OC代码
分类.h


#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger,VZAttributedInsertType) {
    VZAttributedInsertTypeFirst,
    VZAttributedInsertTypeLast
};
@interface NSMutableAttributedString (VZMAttStr)
///文本最前面或最后面插入图片
- (instancetype)initWithImageName:(NSString *)imageName andStringWithContentString:(NSString *)contentString andWithAttributedInsertType:(VZAttributedInsertType) type andLabel:(UILabel *)label;
///文本最前面插入图片
+ (instancetype)attributedWithImageName:(NSString *)imageName andStringWithContentString:(NSString *)contentString andWithAttributedInsertType:(VZAttributedInsertType) type andLabel:(UILabel *)label;
///发送图片
- (instancetype)initWithImg:(UIImage *)image;
///发送图片
+ (instancetype)attributedWithImg:(UIImage *)image;

///回复内容改变指定文字的颜色
- (instancetype)initwithColorString:(NSString *)colorString andColor:(UIColor *)color andContentString:(NSString *)contentString;
///回复内容改变指定文字的颜色
+ (instancetype)attributedWithColorString:(NSString *)colorString Color:(UIColor *)color andContentString:(NSString *)contentString;
///根据文字内容修改指定的文字的颜色
- (instancetype)initwithContent:(NSString *)content andColor:(UIColor *)color andColorString:(NSString *)colorString;
///根据文字内容修改指定的文字的颜色
+ (instancetype)attributedWithContent:(NSString *)content andColor:(UIColor *)color andColorString:(NSString *)colorString;

@end
//用于调整副本显示的位置
@interface VZTextAttachment : NSTextAttachment

@end

@interface NSString (Emoji)
///带图的文本内容
- (NSAttributedString *)emojiAttributedString;
@end

.m文件


#import "NSMutableAttributedString+VZMAttStr.h"

@implementation NSMutableAttributedString (VZMAttStr)
///文本插入图片
- (instancetype)initWithImageName:(NSString *)imageName andStringWithContentString:(NSString *)contentString andWithAttributedInsertType:(VZAttributedInsertType) type andLabel:(UILabel *)label {
    //根据附件生成富文本
    self = [[NSMutableAttributedString alloc] initWithString:contentString];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:imageName];
    //设置(图片)字体大小
    CGFloat attachmentH = label.font.lineHeight;
    attachment.bounds = CGRectMake(0, -3, 25, attachmentH);
    
    NSAttributedString *attString = [NSAttributedString attributedStringWithAttachment:attachment];
    if (type == VZAttributedInsertTypeFirst) {
        [self insertAttributedString:attString atIndex:0];
    } else {
        [self insertAttributedString:attString atIndex:contentString.length];
    }
    
    return self;
}
///文本插入图片
+ (instancetype)attributedWithImageName:(NSString *)imageName andStringWithContentString:(NSString *)contentString andWithAttributedInsertType:(VZAttributedInsertType) type andLabel:(UILabel *)label {
    return [[self alloc] initWithImageName:imageName andStringWithContentString:contentString andWithAttributedInsertType: type andLabel:label];
}
///发送图片
- (instancetype)initWithImg:(UIImage *)image {
    //根据附件生成富文本
    self = [[NSMutableAttributedString alloc] init];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置(图片)字体大小
    NSAttributedString *attString = [NSAttributedString attributedStringWithAttachment:attachment];
    
    [self insertAttributedString:attString atIndex:0];
    return self;
}
///发送图片
+ (instancetype)attributedWithImg:(UIImage *)image {
    return [[self alloc ] initWithImg:image];
}
///改变指定文字的颜色
- (instancetype)initwithColorString:(NSString *)colorString andColor:(UIColor *)color andContentString:(NSString *)contentString {
    NSString *ContentStr = [NSString stringWithFormat:@"%@:%@",colorString,contentString];
    
    NSMutableAttributedString *ContentAttStr = [[NSMutableAttributedString alloc] initWithString:ContentStr];
    NSRange range = [ContentStr rangeOfString:[NSString stringWithFormat:@"%@:",colorString]];
    [ContentAttStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    return ContentAttStr;
}
///改变指定文字的颜色
+ (instancetype)attributedWithColorString:(NSString *)colorString Color:(UIColor *)color andContentString:(NSString *)contentString {
    return [[self alloc] initwithColorString:colorString andColor:color andContentString:contentString];
}

///根据文字内容修改指定的文字的颜色
- (instancetype)initwithContent:(NSString *)content andColor:(UIColor *)color andColorString:(NSString *)colorString {
    NSMutableAttributedString *ContentAttStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = [content rangeOfString:colorString];
    [ContentAttStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    return ContentAttStr;
}
///根据文字内容修改指定的文字的颜色
+ (instancetype)attributedWithContent:(NSString *)content andColor:(UIColor *)color andColorString:(NSString *)colorString{
    return [[self alloc] initwithContent:content andColor:color andColorString:colorString];
}

@end
//根据Label的字体大小自适应图片的显示大小
@implementation VZTextAttachment
- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex {
    return CGRectMake(0,-lineFrag.size.height * 0.2, lineFrag.size.height,lineFrag.size.height);
}
@end

@implementation NSString (Emoji)
///带图的文本内容
- (NSAttributedString *)emojiAttributedString {
    NSArray *plistArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"emoticon.plist" ofType:nil]];
        
    //可变的属性文本
    NSMutableAttributedString *attContent = [[NSMutableAttributedString alloc] initWithString:self];
    
    //  1.通过正则表达式取出表情图片的名称
    NSString *pattern = @"\\[\\w+?\\]";
    NSError *error = nil;
    NSRegularExpression *regx = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (error) {
        NSLog(@"%@",error);
        return attContent;
    }
    
    // 获的匹配结果
//  __block NSString *emoticonName;
    
    NSArray<NSTextCheckingResult *> *results = [regx matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    for (NSTextCheckingResult *result in results) {
        NSString *resultStr = [self substringWithRange:result.range];
        
        [plistArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *desStr = obj[@"des"];
            //取出字符串对应的名字
            if ([desStr isEqualToString:resultStr]) {
                
                 NSString *emoticonName = obj[@"name"];
                
                VZTextAttachment *attachment = [[VZTextAttachment alloc] init];
                attachment.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@@2x.gif",emoticonName]];
               
                NSAttributedString *emojiStr = [NSAttributedString attributedStringWithAttachment:attachment];
                
                [attContent replaceCharactersInRange:result.range withAttributedString:emojiStr];
            }
        }];
        
    }
    return attContent;
}
@end

注意啦:觉得可以的话就star我吧💕💕,你的支持就是我学习和提升的动力;如果有什么需要改进的就给我留言吧,谢谢啦...😁😁

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容