前言
苹果有一个原生的Kit,专门处理图文编辑的事情。这个TextKit使用在文章信息类的App应该是非常重要的。
请下载Demo学习。 https://github.com/WuChuming/TextKitDemo
本文的学习过程
1.TextKit的效果
2.NSMutableAttributedString的使用
3.TextKit的理解
4.键盘表情的实现思路
1.TextKit的效果
2.NSMutableAttributedString的使用
a.AttributedString的属性
NSFontAttributeName 字体
NSForegroundColorAttributeNam字体颜色
NSBackgroundColorAttributeName 背景颜色
NSParagraphStyleAttributeName 段落
NSKernAttributeName 字间距
NSStrikethroughStyleAttributeName 删除线
NSUnderlineStyleAttributeName 下划线
NSStrokeColorAttributeName 边线颜色
NSStrokeWidthAttributeName 边线宽度
NSShadowAttributeName 阴影
NSVerticalGlyphFormAttributeName 横竖排版
属性设置的方式
NSMutableDictionary *arrDic = [NSMutableDictionary dictionary]; arrDic[NSForegroundColorAttributeName] = [UIColor purpleColor]; arrDic[NSBackgroundColorAttributeName] = [UIColor greenColor]; arrDic[NSKernAttributeName] = @10; arrDic[NSUnderlineStyleAttributeName] = @1; NSMutableAttributedString *attriOneStr = [[NSMutableAttributedString alloc]initWithString:@"今天天气真好,蓝天白云,阳光明媚" attributes:arrDic]; self.oneLabel.attributedText = attriOneStr;
添加属性
[attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:36] range:[str rangeOfString:@"bold"]];
删除属性
[attributedString removeAttribute:NSFontAttributeName range:[str rangeOfString:@"little"]];
3.TextKit的理解
TextKit三个重要的类
NSTextContainer 所做的所有工作都是在为 NSLayoutManager提供布局信息或者说是布局建议。NSTextContainer所做的仅仅是指明文本显示的区域,并且不接受任何超出区域的文本。
NSTextStorage保存并管理UITextView要展示的文字内容,该类是NSMutableAttributedString的子类,由于可以灵活地往文字添加或修改属性,所以非常适用于保存并修改文字属性。
NSLayoutManager用于管理NSTextStorage其中的文字内容的排版布局。
以上三者是相互包含相互作用的层次关系。
类的关系
使用的顺序
1.创建了一个自定义的text storage对象,并通过attributed string保存了需要显示的内容;
2.创建了一个layout manager对象;
3.创建了一个text container对象并将它与layout manager关联,然后该text container再和text storage对象关联;
4.通过text container创建了一个text view并显示。
这里只做了Textkit三个类的解析。具体实现方式,请查看上面链接的Demo。
总结
通过使用textKit,我们可以实现排版,自定义文本显示样式,可以统一编写,开放接口,编辑所有个性化的文本样式!