美文网首页iOS Developer
iOS富文本图文混排(NSMutableAttributedSt

iOS富文本图文混排(NSMutableAttributedSt

作者: OpenLee | 来源:发表于2016-11-09 20:00 被阅读1414次

    说明:旨在减少对第三方的依赖,一个比较简单的实现思路;比起像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我吧💕💕,你的支持就是我学习和提升的动力;如果有什么需要改进的就给我留言吧,谢谢啦...😁😁

    相关文章

      网友评论

        本文标题:iOS富文本图文混排(NSMutableAttributedSt

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