iOS富文本圖文混排(NSMutableAttributedString分類實(shí)現(xiàn))

說(shuō)明:旨在減少對(duì)第三方的依賴,一個(gè)比較簡(jiǎn)單的實(shí)現(xiàn)思路;比起像YYLabel等強(qiáng)大的框架只是冰山一角!重在學(xué)習(xí)????(swift和objectC都有提供哦)

廢話不都說(shuō)直接上代碼 (git的demo,點(diǎn)擊下載

我就寫一下swift的具體代碼,OC的就不啰嗦啦

在控制器的實(shí)現(xiàn)代碼,很隨意

//
//  ViewController.swift
//  KVAttributedString
//
//  Created by 李康衛(wèi) on 16/11/8.
//  Copyright ? 2016年 李康衛(wèi). All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //設(shè)置UI
        setupUI()
//        testLabel.attributedText = NSMutableAttributedString.init(imageName: "compose_mentionbutton_background_highlighted", contentString: "helloMISSBodyMeimi", attributedInsertType: KVAttributedInsertType.First, label: testLabel)
//        testLabel.attributedText = NSMutableAttributedString.init(content: "還是短發(fā)hi阿薩[微笑]防守打法看見就看發(fā)的啥看法", color: UIColor.redColor(), colorString: "見就看發(fā)的")
        let nsStr =  "還是短發(fā)hi阿薩[微笑]防守打法看見就看發(fā)的啥看法還是短發(fā)hi阿薩[微笑]防守打法看見就看發(fā)的啥看法還是短發(fā)hi阿薩[微笑]防守打法看見就看發(fā)的啥看法" 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;
    }()
}

每種方法對(duì)應(yīng)的效果如圖所示
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)
        //根據(jù)附件生成富文本
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named:imageName)
//        //設(shè)置(圖片)字體大小
        let attachmentH = label.font.lineHeight
        //調(diào)節(jié)圖片的大小
        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)
        }
        
    }
    ///根據(jù)文字內(nèi)容修改指定的文字的顏色
    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.通過(guò)正則表達(dá)式取出表情圖片的名稱\[\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
        }
        
        // 獲的匹配結(jié)果
        //        __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"])!
                    //必須要注意強(qiáng)拆,需要多打印調(diào)試
                    print("\(emotionName!)@2x.gif")
                    let attachment = NSTextAttachment();
                    //設(shè)置(圖片)字體大小根據(jù)需要作調(diào)整
                    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;
///發(fā)送圖片
- (instancetype)initWithImg:(UIImage *)image;
///發(fā)送圖片
+ (instancetype)attributedWithImg:(UIImage *)image;

///回復(fù)內(nèi)容改變指定文字的顏色
- (instancetype)initwithColorString:(NSString *)colorString andColor:(UIColor *)color andContentString:(NSString *)contentString;
///回復(fù)內(nèi)容改變指定文字的顏色
+ (instancetype)attributedWithColorString:(NSString *)colorString Color:(UIColor *)color andContentString:(NSString *)contentString;
///根據(jù)文字內(nèi)容修改指定的文字的顏色
- (instancetype)initwithContent:(NSString *)content andColor:(UIColor *)color andColorString:(NSString *)colorString;
///根據(jù)文字內(nèi)容修改指定的文字的顏色
+ (instancetype)attributedWithContent:(NSString *)content andColor:(UIColor *)color andColorString:(NSString *)colorString;

@end
//用于調(diào)整副本顯示的位置
@interface VZTextAttachment : NSTextAttachment

@end

@interface NSString (Emoji)
///帶圖的文本內(nèi)容
- (NSAttributedString *)emojiAttributedString;
@end

.m文件


#import "NSMutableAttributedString+VZMAttStr.h"

@implementation NSMutableAttributedString (VZMAttStr)
///文本插入圖片
- (instancetype)initWithImageName:(NSString *)imageName andStringWithContentString:(NSString *)contentString andWithAttributedInsertType:(VZAttributedInsertType) type andLabel:(UILabel *)label {
    //根據(jù)附件生成富文本
    self = [[NSMutableAttributedString alloc] initWithString:contentString];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:imageName];
    //設(shè)置(圖片)字體大小
    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];
}
///發(fā)送圖片
- (instancetype)initWithImg:(UIImage *)image {
    //根據(jù)附件生成富文本
    self = [[NSMutableAttributedString alloc] init];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //設(shè)置(圖片)字體大小
    NSAttributedString *attString = [NSAttributedString attributedStringWithAttachment:attachment];
    
    [self insertAttributedString:attString atIndex:0];
    return self;
}
///發(fā)送圖片
+ (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];
}

///根據(jù)文字內(nèi)容修改指定的文字的顏色
- (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;
}
///根據(jù)文字內(nèi)容修改指定的文字的顏色
+ (instancetype)attributedWithContent:(NSString *)content andColor:(UIColor *)color andColorString:(NSString *)colorString{
    return [[self alloc] initwithContent:content andColor:color andColorString:colorString];
}

@end
//根據(jù)Label的字體大小自適應(yīng)圖片的顯示大小
@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)
///帶圖的文本內(nèi)容
- (NSAttributedString *)emojiAttributedString {
    NSArray *plistArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"emoticon.plist" ofType:nil]];
        
    //可變的屬性文本
    NSMutableAttributedString *attContent = [[NSMutableAttributedString alloc] initWithString:self];
    
    //  1.通過(guò)正則表達(dá)式取出表情圖片的名稱
    NSString *pattern = @"\\[\\w+?\\]";
    NSError *error = nil;
    NSRegularExpression *regx = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (error) {
        NSLog(@"%@",error);
        return attContent;
    }
    
    // 獲的匹配結(jié)果
//  __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"];
            //取出字符串對(duì)應(yīng)的名字
            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我吧????,你的支持就是我學(xué)習(xí)和提升的動(dòng)力;如果有什么需要改進(jìn)的就給我留言吧,謝謝啦...????

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容