在开发中要使用到很多的富文本或者属性字符串,原来使用的是TTTAttributedLabel,现在的项目中使用YYText

YYText 是在 iOS 上显示和编辑富文本的文本框架。

特性:

  • API 兼容 UILabel 和 UITextView
  • 支持高性能的异步排版和渲染
  • 扩展了 CoreText 的属性以支持更多文字效果
  • 支持 UIImage、UIView、CALayer 作为图文混排元素
  • 支持添加自定义样式的、可点击的文本高亮范围
  • 支持自定义文本解析 (内置简单的 Markdown/表情解析)
  • 支持文本容器路径、内部留空路径的控制
  • 支持文字竖排版,可用于编辑和显示中日韩文本
  • 支持图片和富文本的复制粘贴
  • 文本编辑时,支持富文本占位符
  • 支持自定义键盘视图
  • 撤销和重做次数的控制
  • 富文本的序列化与反序列化支持
  • 支持多语言,支持 VoiceOver
  • 全部代码都有文档注释

Gitee代码: YYText: YYText 是在 iOS 上显示和编辑富文本的文本框架 (gitee.com)


主要代码分析

String group

1. YYTextAttribute

作用 NSAttributeName类,YY在这里将AttributeType分为四种种typedef NS_OPTIONS(NSInteger, YYTextAttributeType) {YYTextAttributeTypeNone = 0,YYTextAttributeTypeUIKit = 1 << 0, ///< UIKit attributes, such as UILabel/UITextField/drawInRect.YYTextAttributeTypeCoreText = 1 << 1, ///< CoreText attributes, used by CoreText.YYTextAttributeTypeYYText = 1 << 2, ///< YYText attributes, used by YYText.};YYTextBackedString ——> 作为NSMutableAttrubuteString 的类簇之一,用来将emoji之类的映射为String,对应YYTextBackedStringAttributeNameYYTextBinding ——>作为NSMutableAttrubuteString 的类簇之一,将对应的字符绑定,具体效果参考demo,对应YYTextBindingAttributeNameYYTextShadow ——> 加阴影等效果,对应YYTextShadowAttributeName || YYTextInnerShadowAttributeNameYYTextDecoration ——> 修饰字符,对应YYTextUnderlineAttributeName or YYTextStrikethroughAttributeNameYYTextBorder 边框效果,对应YYTextBackgroundBorderAttributeName or YYTextBorderAttributeNameYYTextAttachment 类似 NSAttchment 对应 YYTextAttachmentAttributeNameYYTextHighlight 高亮效果,对应YYTextHighlightAttributeName,对应的有tapAction回调与,longPressAction回调 在YYLabel中可以看到 longPressAction时间定义为0.5 (#define kLongPressMinimumDuration 0.5 // Time in seconds the fingers must be held down for long press gesture.)

2.YYTextArchiver

里面有几种解析器YYTextSimpleMarkdownParser,YYTextSimpleEmoticonParser,比较重要的是YYTextParser,有所选择文本的回调

3.YYTextRunDelegate

字形的回调 里面有CTRundelegate这么一个方法来获得CTRundelegate(获得之后需要使用CFReleased来释放),并且有属性可以获得字形的ascent descent width

4.YYTextRubyAnnotation

iOS8新增的CTRubyAnnotationRef 关于增加音标等方法

Component Group

YYTextLayout

YYTextContainer —–> 文字容器类 主要布局设置 主体container、边距设置container insets、内部container exclusion path,以及是否竖排版等一系列设置YYTextLinePositionModifier(protocol) —–> 排版完成之前进行回调,调用时要保证线程安全YYTextLinePositionSimpleModifier —–> 对每行排版进行赋值,统一行高YYTextLayout —–> 可以分别根据YYTextContainer or size,以及 NSAttributeString 获得YYTextLayout,YYTextLayout里面有一对只读的属性,类似对应CTFrameRef、CTFramesetterRef…等相关的布局属性,可以将这个layout draw在context,或者View,或者layer上,有些有主线程限制

实际运用

下载 YYText 文件夹内的所有内容。将 YYText 内的源文件添加(拖放)到工程。

链接以下 frameworks:

UIKit

CoreFoundation

CoreText

QuartzCore

Accelerate

MobileCoreServices

导入 YYText.h。

如果无点击效果的富文本文件:

#define rgba(a,b,c,d) [UIColor colorWithRed:a/255. green:b/255. blue:c/255. alpha:d]
#define kThemeColor rgba(255, 41, 65, 1)UILabel *sumPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(15., 15., 200., 15.)];
{NSMutableAttributedString *text = [[NSMutableAttributedString alloc]     initWithString:@"合计:"];//设置字体颜色text.yy_color = rgba(140, 140, 140, 1); //此处是宏定义//设置字体字号text.yy_font = [UIFont systemFontOfSize:15.];NSMutableAttributedString *one = [[NSMutableAttributedString alloc]     initWithString:@"¥"];one.yy_color = kThemeColor; //此处是宏定义one.yy_font = [UIFont systemFontOfSize:11.];NSMutableAttributedString *two = [[NSMutableAttributedString alloc]     initWithString:@"105.00"];two.yy_color = kThemeColor;two.yy_font = [UIFont systemFontOfSize:17.];//将三段不同的文本拼接在一起[text appendAttributedString:one];[text appendAttributedString:two];//然后设置UILabel的attributeText即可sumPriceLabel.attributedText = text;
}

对于有点击事项的富文本,在对应可点击字段的设置中加入点击范围和点击事件:

{NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:@"文字"];one.yy_lineSpacing = 2.5;one.yy_font = SYSTEMFONT(font);one.yy_color = rgba(84, 84, 84, 1);//设置点击范围以及点击事件(必须先设置好然后再将富文本设置给YYLabel才可以生效)[one yy_setTextHighlightRange:one.yy_rangeOfAllcolor:rgba(84, 84, 84, 1)backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220]tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){//自定义代码,此处根据需要调整}];[text appendAttributedString:one];}

主要区别为在定义颜色后加了点击设置代码.

主要注意的是:富文本设置点击范围以及点击事件,必须先设置好然后再将富文本设置给YYLabel才可以生效。

接下来就建一个YYLabel类的label对象,将上面拼接好的富文本设置给它就可

YYLabel *label = [YYLabel new];//将上面的富文本设置过来label.attributedText = text;//设置Label的水平对齐格式label.textAlignment = NSTextAlignmentCenter;//设置垂直对齐格式label.textVerticalAlignment = YYTextVerticalAlignmentCenter;//设置行数,0为多行label.numberOfLines = 0;

详细使用方法

1.基础用法

// YYLabel(类似于UILabel)
YYLabel * label = [YYLabel new ];
label.frame = ...
label.font = ...
label.textColor = ...
label.textAlignment = ...
label.lineBreakMode = ...
label.numberOfLines = ...
label.text = ...// YYTextView(类似于UITextView)
YYTextView * textView = [YYTextView new ];
textView.frame = ...
textView.font = ...
textView.textColor = ...
textView.dataDetectorTypes = ...
textView.placeHolderText = ...
textView.placeHolderTextColor = ...
textView.delegate = ...

2.富文本

// 1.创建属性字符串。
NSMutableAttributedString * text = [[ NSMutableAttributedString  alloc ] initWithString:@“ Some Text,blabla ... ” ];// 2.将属性设置为文本,您几乎可以使用所有CoreText属性。
text.yy_font = [UIFont boldSystemFontOfSize:30 ];
text.yy_color = [UIColor blueColor ];
[文本yy_setColor: [的UIColor redColor ] 范围:NSMakeRange(0,4)];
text.yy_lineSpacing = 10 ;// 3.设置为YYLabel或YYTextView。
YYLabel * label = [YYLabel new ];
label.frame = ...
label.attributedString = text;YYTextView * textView = [YYTextView new ];
textView.frame = ...
textView.attributedString = text;

3.文本高亮

你可以用一些便利的方法设置文本高亮[text yy_setTextHighlightRange:rangecolor:[UIColor blueColor]backgroundColor:[UIColor grayColor]tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){ NSLog(@"tap text range:..."); }];
或者使用自定义配置设置文本高亮显示:// 1.为文本创建“突出显示”属性。
YYTextBorder * border = [YYTextBorder borderWithFillColor: [UIColor grayColor ] cornerRadius:3 ];YYTextHighlight * highlight = [YYTextHighlight new ];
[highlight setColor: [UIColor whiteColor ]];
[突出显示setBackgroundBorder: highlightBorder];
highlight.tapAction = ^(UIView * containerView,NSAttributedString * text,NSRange range,CGRect rect){NSLog(@“ tap text range:... ”); //您还可以将动作处理程序设置为YYLabel或YYTextView。
};// 2.将“突出显示”属性添加到一系列文本中。
[attributionText yy_setTextHighlight: highlight range: highlightRange];// 3.将文本设置为标签或文本视图。
YYLabel * label = ...
label.attributedText = attributedTextYYTextView * textView = ...
textView.attributedText = ...// 4.接收用户交互操作。
label.highlightTapAction = ^(UIView * containerView, NSAttributedString * text, NSRange range, CGRect rect){NSLog( @“ tap text range:... ”);
};
label.highlightLongPressAction = ^(UIView * containerView,NSAttributedString * text,NSRange range,CGRect rect){NSLog(@“ long press text range:... ”);
};@UITextViewDelegate
- (void)textView:(YYTextView *)textView didTapHighlight:(YYTextHighlight *)高亮显示inRange :( NSRange)characterRange rect :( CGRect)rect {NSLog(@“ tap text range:... ”);
}
- (void)textView:(YYTextView *)textView didLongPressHighlight:(YYTextHighlight *)高亮显示inRange :( NSRange)characterRange rect :( CGRect)rect {NSLog(@“ long press text range:... ”);
}

4.文本附件

NSMutableAttributedString * text = [ NSMutableAttributedString  new ];
UIFont * font = [UIFont systemFontOfSize :16 ];
NSMutableAttributedString * attachment = nil ;// UIImage附件
UIImage * image = [UIImage imageNamed:@“ dribbble64_imageio ” ];
attachment = [ NSMutableAttributedString  yy_attachmentStringWithContent: image contentMode: UIViewContentModeCenter attachmentSize: image.size alignToFont: font alignment: YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];// UIView附件
UISwitch * switcher = [UISwitch new ];
[switcher sizeToFit ];
attachment = [ NSMutableAttributedString  yy_attachmentStringWithContent: switcher contentMode: UIViewContentModeBottom attachmentSize: switcher.size alignToFont: font alignment: YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];// CALayer附件
CASharpLayer * layer = [CASharpLayer layer ];
layer.path = ...
attachment = [ NSMutableAttributedString  yy_attachmentStringWithContent: layer contentMode: UIViewContentModeBottom attachmentSize: switcher.size alignToFont: font alignment: YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];

5.文本布局计算

NSAttributedString * text = ...CGSize size = CGSizeMake(100,CGFLOAT_MAX);
YYTextLayout * layout = [YYTextLayout layoutWithContainerSize: size text: text];//获取文本边界
layout.textBoundingRect; //获取边界rect
layout.textBoundingSize; //获得边界大小//查询文本布局
[布局 lineIndexForPoint:CGPointMake( 10, 10)];
[布局closestLineIndexForPoint:CGPointMake(10,10)];
[布局closestPositionToPoint:CGPointMake(10,10)];
[布局textRangeAtPoint:CGPointMake(10,10)];
[布局rectForRange: [YYTextRange rangeWithRange:NSMakeRange(10,2)]];
[布局selectionRectsForRange: [YYTextRange rangeWithRange:NSMakeRange(10,2)]];//文本布局显示
YYLabel * label = [YYLabel new ];
label.size = layout.textBoundingSize;
label.textLayout = layout;

6.调整文本行位置

//便捷方法:
// 1.创建文本行位置修饰符,实现`YYTextLinePositionModifier`协议。
// 2.将其设置为标签或文本视图。YYTextLinePositionSimpleModifier * modifier = [YYTextLinePositionSimpleModifier new ];
modifier.fixedLineHeight = 24 ;YYLabel * label = [YYLabel new ];
label.linePositionModifier = modifier;//完全控制
YYTextLinePositionSimpleModifier * modifier = [YYTextLinePositionSimpleModifier new ];
modifier.fixedLineHeight = 24 ;YYTextContainer * container = [YYTextContainer new ];
container.size = CGSizeMake(100,CGFLOAT_MAX);
container.linePositionModifier = modifier;YYTextLayout * layout = [YYTextLayout layoutWithContainer: container text: text];
YYLabel * label = [YYLabel new ];
label.size = layout.textBoundingSize;
label.textLayout = layout;

7.异步布局和渲染

//如果遇到性能问题,
//可以启用异步显示模式。
YYLabel * label = ...
label.displaysAsynchronously = YES ;//如果你想获得最高的性能,你应该做的
//文本布局使用`在后台线程YYTextLayout`类。
YYLabel * label = [YYLabel new ];
label.displaysAsynchronously = YES ;
label.ignoreCommonProperties = YES ;dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {//创建属性字符串.NSMutableAttributedString * text = [[ NSMutableAttributedString  alloc ] initWithString:@“ Some Text ” ];文本。yy_font = [UIFont systemFontOfSize :16 ];文本。yy_color = [UIColor grayColor ];[文本yy_setColor: [的UIColor redColor ] 范围:NSMakeRange(0,4)];//创建文本容器 YYTextContainer * container = [YYTextContainer new ];容器。size = CGSizeMake(100,CGFLOAT_MAX);容器。maximumNumberOfRows = 0 ;//生成文本布局。YYTextLayout * layout = [YYTextLayout layoutWithContainer: container text: text];dispatch_async(dispatch_get_main_queue(),^ {标签。size =布局。textBoundingSize ;标签。textLayout = layout;});
});

8.文本容器控件

YYLabel * label = ...
label.textContainerPath = [UIBezierPath bezierPathWith ...];
label.exclusionPaths = @ [[UIBezierPath bezierPathWith ...];,...];
label.textContainerInset = UIEdgeInsetsMake(...);
label.verticalForm = YES / NO ;YYTextView * textView = ...
textView.exclusionPaths = @ [[UIBezierPath bezierPathWith ...];,...];
textView.textContainerInset = UIEdgeInsetsMake(...);
textView.verticalForm = YES / NO ;

9.文本解析器

// 1.创建文本解析器YYTextSimpleEmoticonParser * parser = [YYTextSimpleEmoticonParser new ];
NSMutableDictionary * mapper = [ NSMutableDictionary  new ];
mapper [ @“:smile:” ] = [UIImage imageNamed:@“ smile.png ” ];
mapper [ @“:cool:” ] = [UIImage imageNamed:@“ cool.png ” ];
mapper [ @“:cry:” ] = [UIImage imageNamed:@“ cry.png ” ];
mapper [ @“:wink:” ] = [UIImage imageNamed:@“ wink.png ” ];
parser.emoticonMapper = mapper;YYTextSimpleMarkdownParser * parser = [YYTextSimpleMarkdownParser new ];
[parser setColorWithDarkTheme ];MyCustomParser * parser = ... //自定义解析器// 2.将解析器附加到标签或文本视图
YYLabel * label = ...
label.textParser = parser;YYTextView * textView = ...
textView.textParser = parser;

10.调试

//设置共享调试选项以显示文本布局结果。
YYTextDebugOption * debugOptions = [YYTextDebugOption new ];
debugOptions.baselineColor = [UIColor redColor ];
debugOptions.CTFrameBorderColor = [UIColor redColor ];
debugOptions.CTLineFillColor = [UIColor colorWithRed:0.000  绿色:0.463  蓝色:1.000  alpha:0.180 ];
debugOptions.CGGlyphBorderColor = [UIColor colorWithRed:1.000  green:0.524  blue:0.000  alpha:0.200 ];
[YYTextDebugOption setSharedDebugOption: debugOptions];

YYText的介绍和使用相关推荐

  1. yytextview多种格式_YYKit之YYText

    原文:http://www.cnblogs.com/lujianwenance/p/5716804.html 本文的目的是希望能帮助到我们更快的熟悉和学习YYText的结构和实现的思路,如有不正确或者 ...

  2. Lex 与 Yacc 介绍(Ashish Bansal )

    Lex 与 Yacc 介绍 转贴自http://www-900.ibm.com/developerWorks/cn/linux/sdk/lex/index.shtml Ashish Bansal 软件 ...

  3. 服务器开发27:log4c充当服务器跨平台日志库(cmake跨平台编译,配置介绍及代码封装)

    文章目录 一.跨平台编译 1)编译准备 (1)expat编译 2)原生linux编译.安装 3)cmake跨平台编译 二.log4c配置笔记 1)与log4cpp\log4cxx的比较 2)log4c ...

  4. iOS tableView性能优化之异步排版和绘制渲染----YYText框架学习(YYTextAsyncLayer)

    YYWebImage源码分析 YYImage源码 YYModel源码解析 前言 这段时间针对设计架构,解耦以及性能优化相关的知识点看了不少,前两者可以看MVVM和AOP编程思路,最后一个是昨天看的,Y ...

  5. iOS 开源项目介绍之UI篇

    本文介绍一些UI方面的开源项目,大家可以结合自己的需求选择合适的开源库进行使用和学习.大家也可以关注我的公众号阅读此文章.                                       ...

  6. 简单介绍互联网领域选择与营销方法

    在我看来,互联网领域的选择是"安家",而营销方法的不同则表现了"定家"的方式多种多样,只有选对了,"家"才得以"安定". ...

  7. 常用开源协议介绍以及开源软件规范列表

    1. 开源协议介绍 GPL: General Public License,开源项目最常用的许可证,衍生代码的分发需开源并且也要遵守此协议.该协议也有很多变种,不同变种要求会略微不同. MPL: MP ...

  8. python:Json模块dumps、loads、dump、load介绍

    20210831 https://www.cnblogs.com/bigtreei/p/10466518.html json dump dumps 区别 python:Json模块dumps.load ...

  9. pytorch学习笔记(九):PyTorch结构介绍

    PyTorch结构介绍 对PyTorch架构的粗浅理解,不能保证完全正确,但是希望可以从更高层次上对PyTorch上有个整体把握.水平有限,如有错误,欢迎指错,谢谢! 几个重要的类型 和数值相关的 T ...

  10. Python字节码介绍

    了解 Python 字节码是什么,Python 如何使用它来执行你的代码,以及知道它是如何帮到你的. 如果你曾经编写过 Python,或者只是使用过 Python,你或许经常会看到 Python 源代 ...

最新文章

  1. H3 BPM钉钉接入配置
  2. /* * 编程第二题(20分): 一球从100米高度自由落下,每次落地后反跳回原高度的一半,再落下。求它在第十次落地时,共经过多少米?第十次反弹多高? */
  3. Python序列的增量赋值
  4. 标准化条件变量 -- condition_variable
  5. 用特征码秒杀各程序语言按钮事件
  6. sklearn自学指南(part17)--稳健回归-异常值和建模误差
  7. AddTransient、AddSingleton、AddScoped 三者都应该在什么场景下使用
  8. not in和not exist的区别(转)
  9. ESP32开发板开源啦 ESP32-IOT-KIT全开源物联网开发板
  10. python中类的定义和使用_Python中类的定义与使用
  11. 使用ConnectivityManager 判断网络是否连接
  12. 富士康计算机主板官网,富士康主板官网?富士康主板刷bios工具?foxconn主板官网?富士康主板怎么样...
  13. arcgis拓扑检查和修改
  14. WORD宏VBA:标题应用样式+图表统一应用格式且居中
  15. 打印机驱动无法安装到计算机是,电脑打印机无法安装驱动的解决方法
  16. Movist Pro for Mac 2.2.16 — 播放器
  17. java微信平台验证票据
  18. java bt下载_bt: Java种子下载程序
  19. 学习日记day17 ps
  20. Excel 批量重命名照片

热门文章

  1. vs2012 安装 InstallShield
  2. VS2012下载网址
  3. python爬网易云音乐评论最多的歌_Python爬取网易云音乐上评论火爆的歌曲
  4. 2019年12月7日pmp考试成都在哪考
  5. Centos7 更换阿里yum源
  6. 计算机联锁车务仿真培训系统 casco模式,计算机联锁仿真培训系统
  7. 千月双端影视app源码 后端是Thinkphp
  8. oracle 建表 varchar,一个完整的Oracle建表的例子
  9. tp5利用mysql数据库去重
  10. 使用Postman工具进行简单的Get/Post测试