iOS YYText的使用笔记二(YYLabel聊天表情+文字并排)
来源:互联网 发布:韩家炜 数据挖掘 pdf 编辑:程序博客网 时间:2024/05/19 18:16
上一篇博客记录了一个图文编辑器的功能(YYTextview的使用),接下来记录一下YYLabel的简单使用,
其实他们的图文并排的原理都是一样的 都是NSMutableAttributedString来处理富文本
之前用TQRichTextView实现过emoji表情+文字 虽然性能还行,但是 计算文本高度是一个让我非常头疼的问题,经常容易算不准,表情的大小很难调整,今天YYLabel简单了实现了一下他的emoji表情+文字的列表排布,个人感觉相当好用 YYLabel提供计算文本的高度,性能也很好,有个异步渲染的机制,牛逼!
话不多说上代码:
- //
- // UserVC.h
- // YYTextDemo
- //
- // Created by linpeng on 16/3/13.
- // Copyright © 2016年 ibireme. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- @interface UserVC : UIViewController
- @end
- //
- // UserVC.m
- // YYTextDemo
- //
- // Created by linpeng on 16/3/13.
- // Copyright © 2016年 ibireme. All rights reserved.
- //
- #import "UserVC.h"
- #import "YYText.h"
- #import "UIView+YYAdd.h"
- #import "YYImage.h"
- #import "NSBundle+YYAdd.h"
- #import "NSString+YYAdd.h"
- @interface CellModel : NSObject
- @property (nonatomic,strong) YYTextLayout *textLayout;
- @property (nonatomic) CGFloat cellHeight;
- @end
- @implementation CellModel
- @end
- //=====================================分割线=========================================
- @interface UserVCCell : UITableViewCell
- @property (nonatomic,strong) CellModel *data;
- @property (nonatomic, strong) YYLabel *contentLabel;
- @end
- @implementation UserVCCell
- #define kWidth 280
- #define kLabelMarginTop 10
- -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
- {
- self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
- if (self)
- {
- [self addSubview:self.contentLabel];
- }
- return self;
- }
- -(void)setData:(CellModel *)data
- {
- _data = data;
- YYTextLayout *layout = data.textLayout;
- self.contentLabel.textLayout = layout;
- self.contentLabel.size = layout.textBoundingSize;
- }
- -(YYLabel *)contentLabel
- {
- if (_contentLabel == nil) {
- _contentLabel = [[YYLabel alloc] initWithFrame:CGRectMake((kScreenWidth - kWidth)/2.0, kLabelMarginTop, 0, 0)];
- _contentLabel.userInteractionEnabled = YES;
- _contentLabel.numberOfLines = 0;
- UIFont *font = [UIFont systemFontOfSize:16];
- _contentLabel.font = font;
- _contentLabel.displaysAsynchronously = YES; /// enable async display
- _contentLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
- [_contentLabel setBackgroundColor:[[UIColor grayColor] colorWithAlphaComponent:0.2]];
- }
- return _contentLabel;
- }
- @end
- //=====================================分割线=========================================
- @interface UserVC ()<UITableViewDataSource,UITableViewDelegate>
- @property (nonatomic,strong) NSMutableArray *dataList;
- @end
- @implementation UserVC
- NSMutableAttributedString *attributeText;
- - (void)viewDidLoad {
- [super viewDidLoad];
- [self.view setBackgroundColor:[UIColor whiteColor]];
- UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
- [tableView registerClass:[UserVCCell class] forCellReuseIdentifier:@"tableCell"];
- tableView.delegate = self;
- tableView.dataSource = self;
- [self.view addSubview:tableView];
- dispatch_async(dispatch_get_main_queue(), ^{
- NSMutableArray *arrays = [NSMutableArray new];
- for (int i = 0; i<100; i++)
- {
- NSMutableAttributedString *text = [NSMutableAttributedString new];
- NSString *title11 = @"开始 ";
- [text appendAttributedString:[[NSAttributedString alloc] initWithString:title11 attributes:nil]];
- UIFont *font = [UIFont systemFontOfSize:16];
- 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"];
- for (int j = 0;j<names.count && j< arc4random()%names.count ;j++)
- {
- NSString *name = names[j];
- NSString *path = [[NSBundle mainBundle] pathForScaledResource:name ofType:@"png" inDirectory:@"EmoticonQQ.bundle"];
- NSData *data = [NSData dataWithContentsOfFile:path];
- YYImage *image = [YYImage imageWithData:data scale:2];//修改表情大小
- image.preloadAllAnimatedImageFrames = YES;
- YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
- NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
- [text appendAttributedString:attachText];
- if(arc4random()%5==0)
- {
- [text appendAttributedString:[[NSAttributedString alloc] initWithString:@"这是乱七八糟的文字" attributes:nil]];
- }
- }
- [text appendAttributedString:[[NSAttributedString alloc] initWithString:@"结束" attributes:nil]];
- YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kWidth, MAXFLOAT)];
- YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:text];
- CellModel *model = [[CellModel alloc] init];
- model.textLayout = textLayout;
- model.cellHeight = textLayout.textBoundingSize.height;
- [arrays addObject:model];
- }
- self.dataList = arrays;
- //更新UI
- dispatch_async(dispatch_get_main_queue(), ^{
- [tableView reloadData];
- });
- });
- }
- -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *cellID = @"tableCell";
- UserVCCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
- if (!cell)
- {
- cell = [[UserVCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
- }
- CellModel *model = self.dataList[indexPath.row];
- cell.data = model;
- return cell;
- }
- -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- {
- return self.dataList.count;
- }
- -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- CellModel *model = self.dataList[indexPath.row];
- CGFloat height = model.cellHeight;
- return height + 2*kLabelMarginTop;
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- /*
- #pragma mark - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
- // Get the new view controller using [segue destinationViewController].
- // Pass the selected object to the new view controller.
- }
- */
- @end
看效果 我模拟了100条数据 所以数据那用了GCD 然后更新UI
也可以修改表情的大小
YYImage *image = [YYImageimageWithData:datascale:1.5];//修改表情大小
看效果:
ps:正则过滤表情生成NSMutableAttributedString
正常我们使用的时候是通过一串字符串(包含表情的占位符)来对应显示
例如:
[嘻嘻][嘻嘻][嘻嘻]我们[喜欢][喜欢][喜欢]你们[钱][钱][钱]这样[可爱][可爱][可爱]我的小时候[可爱][可爱][可爱][可爱][可爱]
以下利用正则表达式来过滤各个表情的位置
- -(NSMutableAttributedString *)processCommentContent:(NSString *)text
- {
- //转成可变属性字符串
- NSMutableAttributedString * mAttributedString = [[NSMutableAttributedString alloc]init];
- NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
- [paragraphStyle setLineSpacing:4];//调整行间距
- [paragraphStyle setParagraphSpacing:4];//调整行间距
- NSDictionary *attri = [NSDictionary dictionaryWithObjects:@[kCurrentLabelFont,[UIConstants getWordColorC2],paragraphStyle] forKeys:@[NSFontAttributeName,NSForegroundColorAttributeName,NSParagraphStyleAttributeName]];
- [mAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:text attributes:attri]];
- //创建匹配正则表达式的类型描述模板
- NSString * pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
- //创建匹配对象
- NSError * error;
- NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
- //判断
- if (!regularExpression)//如果匹配规则对象为nil
- {
- NSLog(@"正则创建失败!");
- NSLog(@"error = %@",[error localizedDescription]);
- return nil;
- }
- else
- {
- NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
- //开始遍历 逆序遍历
- for (NSInteger i = resultArray.count - 1; i >= 0; i --)
- {
- //获取检查结果,里面有range
- NSTextCheckingResult * result = resultArray[i];
- //根据range获取字符串
- NSString * rangeString = [mAttributedString.string substringWithRange:result.range];
- NSString *imageName = [[KSFaceManager shareManager] reflectFaceIDWithFace:rangeString];
- if (imageName)
- {
- //获取图片
- UIImage * image = [self getImageWithRangeString:imageName];//这是个自定义的方法
- if (image != nil)
- {
- UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
- imageView.width = 23;
- imageView.height = 23;
- NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:[UIFont systemFontOfSize:16] alignment:YYTextVerticalAlignmentCenter];
- //开始替换
- [mAttributedString replaceCharactersInRange:result.range withAttributedString:attachText];
- }
- }
- }
- }
- return mAttributedString;
- }
- //根据rangeString获取plist中的图片
- -(UIImage *)getImageWithRangeString:(NSString *)rangeString
- {
- return [UIImage imageNamed:rangeString];
- }
阅读全文
1 0
- iOS YYText的使用笔记二(YYLabel聊天表情+文字并排)
- iOS YYText的使用笔记二(YYLabel聊天表情+文字并排)
- iOS YYText的使用笔记一(YYTextView图文编辑器)
- iOS YYText的使用笔记一(YYTextView图文编辑器)
- iOS - UILabel点击选中文字,部分高亮,YYLabel
- 使用YYText-文本蓝色文字点击实现超链接跳转
- iOS 使用XMPP框架开发IM聊天模块,实现简单的文字聊天
- 聊天界面: 表情和文字自适应
- 文字视图,类似qq表情聊天
- CRichEditCtrlEx支持静态表情聊天类的使用
- CRichEditCtrlEx支持静态表情聊天类的使用
- CRichEditCtrlEx支持静态表情聊天类的使用
- 图片与文字并排显示的导航
- iphone聊天用几种图形(表情)与文字混排的实现与比较
- iphone聊天用几种图形(表情)与文字混排的实现与比较
- iphone聊天用几种图形(表情)与文字混排的实现与比较
- iphone聊天用几种图形(表情)与文字混排的实现与比较
- iOS开发之YYKit丰富的组件,如:YYText
- Android 7.0 安装包修改后无法安装
- python excel文件数据转成json
- ofbiz局部刷新on-event-update-area(如分页等)
- 【cordova ionic2 微信分享】使用 cordova-plugin-wechat 做微信分享的注意点
- python学习之 数组
- iOS YYText的使用笔记二(YYLabel聊天表情+文字并排)
- 第十四周 项目2-用哈希表组织关键字
- 测试1
- 多元线性回归推导 — Multi-Variable Linear Regression Derivation
- 第十三周 【项目1
- shell 两时间之差
- 链表、队列、栈和字符串的相关应用(四)字符串的替换
- 数据结构第四周项目-循环双链表应用
- 曼哈顿距离