iOS YYText的使用笔记二(YYLabel聊天表情+文字并排)

来源:互联网 发布:韩家炜 数据挖掘 pdf 编辑:程序博客网 时间:2024/05/19 18:16

上一篇博客记录了一个图文编辑器的功能(YYTextview的使用),接下来记录一下YYLabel的简单使用,

其实他们的图文并排的原理都是一样的 都是NSMutableAttributedString来处理富文本

之前用TQRichTextView实现过emoji表情+文字 虽然性能还行,但是 计算文本高度是一个让我非常头疼的问题,经常容易算不准,表情的大小很难调整,今天YYLabel简单了实现了一下他的emoji表情+文字的列表排布,个人感觉相当好用 YYLabel提供计算文本的高度,性能也很好,有个异步渲染的机制,牛逼!

话不多说上代码:

[html] view plain copy
  1. //  
  2. //  UserVC.h  
  3. //  YYTextDemo  
  4. //  
  5. //  Created by linpeng on 16/3/13.  
  6. //  Copyright © 2016年 ibireme. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11. @interface UserVC : UIViewController  
  12.   
  13. @end  

[html] view plain copy
  1. //  
  2. //  UserVC.m  
  3. //  YYTextDemo  
  4. //  
  5. //  Created by linpeng on 16/3/13.  
  6. //  Copyright © 2016年 ibireme. All rights reserved.  
  7. //  
  8.   
  9. #import "UserVC.h"  
  10. #import "YYText.h"  
  11. #import "UIView+YYAdd.h"  
  12. #import "YYImage.h"  
  13. #import "NSBundle+YYAdd.h"  
  14. #import "NSString+YYAdd.h"  
  15.   
  16.   
  17. @interface CellModel : NSObject  
  18.   
  19. @property (nonatomic,strong) YYTextLayout *textLayout;  
  20. @property (nonatomic) CGFloat cellHeight;  
  21.   
  22. @end  
  23.   
  24.   
  25. @implementation CellModel  
  26.   
  27. @end  
  28.   
  29.   
  30. //=====================================分割线=========================================  
  31.   
  32. @interface UserVCCell : UITableViewCell  
  33.   
  34. @property (nonatomic,strong) CellModel *data;  
  35. @property (nonatomic, strong) YYLabel *contentLabel;  
  36.   
  37. @end  
  38.   
  39. @implementation UserVCCell  
  40.   
  41.   
  42. #define kWidth   280  
  43. #define kLabelMarginTop  10  
  44.   
  45. -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier  
  46. {  
  47.     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];  
  48.     if (self)  
  49.     {  
  50.         [self addSubview:self.contentLabel];  
  51.     }  
  52.     return self;  
  53. }  
  54.   
  55. -(void)setData:(CellModel *)data  
  56. {  
  57.     _data = data;  
  58.     YYTextLayout *layout = data.textLayout;  
  59.     self.contentLabel.textLayout = layout;  
  60.     self.contentLabel.size = layout.textBoundingSize;  
  61. }  
  62.   
  63. -(YYLabel *)contentLabel  
  64. {  
  65.     if (_contentLabel == nil) {  
  66.         _contentLabel = [[YYLabel alloc] initWithFrame:CGRectMake((kScreenWidth - kWidth)/2.0, kLabelMarginTop, 0, 0)];  
  67.         _contentLabel.userInteractionEnabled = YES;  
  68.         _contentLabel.numberOfLines = 0;  
  69.          UIFont *font = [UIFont systemFontOfSize:16];  
  70.         _contentLabel.font = font;  
  71.         _contentLabel.displaysAsynchronously = YES; /// enable async display  
  72.         _contentLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;  
  73.         [_contentLabel setBackgroundColor:[[UIColor grayColor] colorWithAlphaComponent:0.2]];  
  74.     }  
  75.     return _contentLabel;  
  76. }  
  77. @end  
  78.   
  79.   
  80.   
  81. //=====================================分割线=========================================  
  82.   
  83.   
  84. @interface UserVC ()<UITableViewDataSource,UITableViewDelegate>  
  85.   
  86. @property (nonatomic,strong) NSMutableArray *dataList;  
  87.   
  88. @end  
  89.   
  90. @implementation UserVC  
  91.   
  92. NSMutableAttributedString *attributeText;  
  93. - (void)viewDidLoad {  
  94.     [super viewDidLoad];  
  95.   
  96.     [self.view setBackgroundColor:[UIColor whiteColor]];  
  97.       
  98.     UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];  
  99.     [tableView registerClass:[UserVCCell class] forCellReuseIdentifier:@"tableCell"];  
  100.     tableView.delegate = self;  
  101.     tableView.dataSource = self;  
  102.     [self.view addSubview:tableView];  
  103.       
  104.     dispatch_async(dispatch_get_main_queue(), ^{  
  105.         NSMutableArray *arrays = [NSMutableArray new];  
  106.         for (int i = 0; i<100; i++)  
  107.         {  
  108.             NSMutableAttributedString *text = [NSMutableAttributedString new];  
  109.             NSString *title11 = @"开始 ";  
  110.             [text appendAttributedString:[[NSAttributedString alloc] initWithString:title11 attributes:nil]];  
  111.             UIFont *font = [UIFont systemFontOfSize:16];  
  112.             NSArray *names = @[@"001", @"022", @"019",@"056",@"085",@"001", @"022", @"019",@"056",@"085",@"001", @"022", @"019",@"056",@"085",@"001", @"022", @"019",@"056",@"085",@"001", @"022",@"001",@"001",@"022",@"022",@"022",@"022",@"022",@"022",@"022",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"022",@"022",@"022",@"022",@"001", @"022", @"019",@"056",@"085",@"001", @"022", @"019",@"056",@"085",@"001", @"022", @"019",@"056",@"085",@"001", @"022", @"019",@"056",@"085",@"001", @"022",@"001",@"001",@"022",@"022",@"022",@"022",@"022",@"022",@"022",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"001",@"022",@"022",@"022",@"022"];  
  113.               
  114.             for (int j = 0;j<names.count && j< arc4random()%names.count ;j++)  
  115.             {  
  116.                 NSString *name  = names[j];  
  117.                 NSString *path = [[NSBundle mainBundle] pathForScaledResource:name ofType:@"png" inDirectory:@"EmoticonQQ.bundle"];  
  118.                 NSData *data = [NSData dataWithContentsOfFile:path];  
  119.                 YYImage *image = [YYImage imageWithData:data scale:2];//修改表情大小  
  120.                 image.preloadAllAnimatedImageFrames = YES;  
  121.                 YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];  
  122.                 NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];  
  123.                 [text appendAttributedString:attachText];  
  124.                 if(arc4random()%5==0)  
  125.                 {  
  126.                     [text appendAttributedString:[[NSAttributedString alloc] initWithString:@"这是乱七八糟的文字" attributes:nil]];  
  127.                 }  
  128.             }  
  129.               
  130.             [text appendAttributedString:[[NSAttributedString alloc] initWithString:@"结束" attributes:nil]];  
  131.             YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kWidth, MAXFLOAT)];  
  132.             YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:text];  
  133.               
  134.             CellModel *model = [[CellModel alloc] init];  
  135.             model.textLayout = textLayout;  
  136.             model.cellHeight = textLayout.textBoundingSize.height;  
  137.             [arrays addObject:model];  
  138.         }  
  139.         self.dataList = arrays;  
  140.         //更新UI  
  141.         dispatch_async(dispatch_get_main_queue(), ^{  
  142.             [tableView reloadData];  
  143.         });  
  144.     });  
  145.       
  146. }  
  147. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  148. {  
  149.     static NSString *cellID = @"tableCell";  
  150.     UserVCCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];  
  151.     if (!cell)  
  152.     {  
  153.         cell = [[UserVCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];  
  154.     }  
  155.     CellModel *model = self.dataList[indexPath.row];  
  156.     cell.data = model;  
  157.     return cell;  
  158. }  
  159. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
  160. {  
  161.     return self.dataList.count;  
  162. }  
  163. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
  164. {  
  165.     CellModel *model = self.dataList[indexPath.row];  
  166.     CGFloat height = model.cellHeight;  
  167.     return height + 2*kLabelMarginTop;  
  168. }  
  169. - (void)didReceiveMemoryWarning {  
  170.     [super didReceiveMemoryWarning];  
  171.     // Dispose of any resources that can be recreated.  
  172. }  
  173.   
  174. /*  
  175. #pragma mark - Navigation  
  176.   
  177. // In a storyboard-based application, you will often want to do a little preparation before navigation  
  178. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {  
  179.     // Get the new view controller using [segue destinationViewController].  
  180.     // Pass the selected object to the new view controller.  
  181. }  
  182. */  
  183.   
  184. @end  

看效果  我模拟了100条数据 所以数据那用了GCD 然后更新UI


也可以修改表情的大小 

 YYImage *image = [YYImageimageWithData:datascale:1.5];//修改表情大小

看效果:


ps:正则过滤表情生成NSMutableAttributedString

正常我们使用的时候是通过一串字符串(包含表情的占位符)来对应显示

例如:

[嘻嘻][嘻嘻][嘻嘻]我们[喜欢][喜欢][喜欢]你们[][][]这样[可爱][可爱][可爱]我的小时候[可爱][可爱][可爱][可爱][可爱]

以下利用正则表达式来过滤各个表情的位置


[html] view plain copy
  1. -(NSMutableAttributedString *)processCommentContent:(NSString *)text  
  2. {  
  3.     //转成可变属性字符串  
  4.     NSMutableAttributedString * mAttributedString = [[NSMutableAttributedString alloc]init];  
  5.     NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];  
  6.     [paragraphStyle setLineSpacing:4];//调整行间距  
  7.     [paragraphStyle setParagraphSpacing:4];//调整行间距  
  8.     NSDictionary *attri = [NSDictionary dictionaryWithObjects:@[kCurrentLabelFont,[UIConstants getWordColorC2],paragraphStyle] forKeys:@[NSFontAttributeName,NSForegroundColorAttributeName,NSParagraphStyleAttributeName]];  
  9.     [mAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:text attributes:attri]];  
  10.     //创建匹配正则表达式的类型描述模板  
  11.     NSString * pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";  
  12.     //创建匹配对象  
  13.     NSError * error;  
  14.     NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];  
  15.     //判断  
  16.     if (!regularExpression)//如果匹配规则对象为nil  
  17.     {  
  18.         NSLog(@"正则创建失败!");  
  19.         NSLog(@"error = %@",[error localizedDescription]);  
  20.         return nil;  
  21.     }  
  22.     else  
  23.     {  
  24.         NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];  
  25.         //开始遍历 逆序遍历  
  26.         for (NSInteger i = resultArray.count - 1; i >= 0; i --)  
  27.         {  
  28.             //获取检查结果,里面有range  
  29.             NSTextCheckingResult * result = resultArray[i];  
  30.             //根据range获取字符串  
  31.             NSString * rangeString = [mAttributedString.string substringWithRange:result.range];  
  32.             NSString *imageName =  [[KSFaceManager shareManager] reflectFaceIDWithFace:rangeString];  
  33.             if (imageName)  
  34.             {                  
  35.                 //获取图片  
  36.                 UIImage * image = [self getImageWithRangeString:imageName];//这是个自定义的方法  
  37.                 if (image != nil)  
  38.                 {  
  39.                     UIImageView *imageView = [[UIImageView alloc] initWithImage:image];  
  40.                     imageView.width = 23;  
  41.                     imageView.height = 23;  
  42.                     NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:[UIFont systemFontOfSize:16] alignment:YYTextVerticalAlignmentCenter];  
  43.                     //开始替换  
  44.                     [mAttributedString replaceCharactersInRange:result.range withAttributedString:attachText];  
  45.                 }    
  46.             }  
  47.         }  
  48.     }  
  49.       
  50.     return mAttributedString;  
  51. }  
  52. //根据rangeString获取plist中的图片  
  53. -(UIImage *)getImageWithRangeString:(NSString *)rangeString  
  54. {  
  55.     return [UIImage imageNamed:rangeString];  
  56. }  
阅读全文
1 0
原创粉丝点击