YYText

1.里面主要两个控件:

YYTextView 和 YYLabel

现在主要是YYTextview的简单使用

YYText主要是NSMutableAttributedString来处理富文本 他的内部实现可以自己去深究。

简单的图文并排,使用NSMutableAttributedString创建一个对象 然后 appendAttributesString来拼接文字和图片(占位)//

//  TextAndImageTextViewVC.h

//  YYTextDemo

//

//  Created by linpeng on 16/3/13.

//  Copyright © 2016年 ibireme. All rights reserved.

//

#import

@interface TextAndImageTextViewVC : UIViewController

@end

//

//  TextAndImageTextViewVC.m

//  YYTextDemo

//

//  Created by linpeng on 16/3/13.

//  Copyright © 2016年 ibireme. All rights reserved.

//

#import "TextAndImageTextViewVC.h"

#import "YYText.h"

#import "UIView+YYAdd.h"

#import "YYTextView.h"

#import "YYImage.h"

#import "NSBundle+YYAdd.h"

#import "NSString+YYAdd.h"

@interface TextAndImageTextViewVC ()

@end

YYTextView *textView;

@implementation TextAndImageTextViewVC

- (void)viewDidLoad {

[super viewDidLoad];

[self.view setBackgroundColor:[UIColor whiteColor]];

textView= [[YYTextView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];

textView.userInteractionEnabled=YES;

textView.textVerticalAlignment=YYTextVerticalAlignmentTop;

textView.size=CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);

//创建最主要的attribute文本

NSMutableAttributedString *contentText= [NSMutableAttributedString new];

UIFont *font= [UIFont systemFontOfSize:16];

//图片资源

YYImage *image= [YYImage imageNamed:@"demo.jpg"];

image.preloadAllAnimatedImageFrames=YES;

//添加文本+图片

[contentText appendAttributedString:[[NSAttributedString alloc] initWithString:@"这是第一站图片" attributes:nil]];

{

YYAnimatedImageView *imageView= [[YYAnimatedImageView alloc] initWithImage:image];

imageView.frame=CGRectMake(0, 0, textView.width - 10, textView.width/image.size.width*image.size.height);

NSMutableAttributedString *attachText= [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageView.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];

[contentText appendAttributedString:attachText];

}

//添加文本+图片

[contentText appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n 接下来是第二张" attributes:nil]];

{

YYAnimatedImageView *imageView2= [[YYAnimatedImageView alloc] initWithImage:image];

imageView2.frame=CGRectMake(0, 0, textView.width - 10, textView.width/image.size.width*image.size.height);

NSMutableAttributedString *attachText2= [NSMutableAttributedString yy_attachmentStringWithContent:imageView2 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageView2.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];

[contentText appendAttributedString:attachText2];

}

textView.attributedText=contentText;

[self.view addSubview:textView];

//获取图片资源

NSArray *attachments=textView.textLayout.attachments;

for(YYTextAttachment *attachment in attachments)

{

YYAnimatedImageView *imageView=attachment.content;

YYImage *image= (YYImage *)imageView.image;

NSLog(@"获取到图片:%@",image);

}

NSArray *attachmentRanges=textView.textLayout.attachmentRanges;

for (NSValue *range in attachmentRanges)

{

NSRanger= [range rangeValue];

NSLog(@"资源所在位置:%ld 长度: %ld",r.location,r.length);

}

}

- (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

以上代码加上注释应该很容易理解就不多讲了  注意 \n 这个换行符的使用

看效果图:

(可编辑的文本+图片 有的app需要编辑文章功能 用这个就个可以大体实现了,图片和文本都已经获取到了 到时后对应传到服务器,之前没用YYTextview也实现过这种功能,效果比较差,用这个实现,相当完美,必须给YYText作者点个赞)

上一篇博客记录了一个图文编辑器的功能(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

@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 ()

@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 (inti=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 (intj=0;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];

CGFloatheight=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


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 (NSIntegeri=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];

}

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

推荐阅读更多精彩内容