创建NSAttributedString属性字典的简单方法
在您的Podfile中添加此行:
pod "MTStringAttributes"
pod? => https://github.com/CocoaPods/CocoaPods/
#include <MTStringAttributes.h>
创建一个属性对象
MTStringAttributes *attributes = [[MTStringAttributes alloc] init];
设置一些基本属性
attributes.font = nil;
attributes.textColor = [UIColor redColor];
attributes.backgroundColor = [UIColor blackColor];
attributes.strikethrough = YES;
attributes.underline = YES;
一些高级功能
attributes.ligatures = YES;
attributes.kern = @(1);
attributes.outlineColor = [UIColor blueColor];
attributes.outlineWidth = @(2);
最后
NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"The attributed string!"
attributes:[attributes dictionary]];
依赖于Slash,MTStringParser允许您向标签添加样式,然后从这些标签的标记中生成有属性的字符串。
#include <MTStringParser.h>
[[MTStringParser sharedParser] addStyleWithTagName:@"red"
font:[UIFont systemFontOfSize:12]
color:[UIColor redColor]];
NSAttributedString *string = [[MTStringParser sharedParser]
attributedStringFromMarkup:@"This is a <red>red section</red>"];
轻松创建一个字符串属性对象
MTStringAttributes *attributes = [[MTStringAttributes alloc] init];
attributes.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
attributes.textColor = [UIColor blackColor];
将此作为即将解析的整个字符串的默认值
[[MTStringParser sharedParser] setDefaultAttributes:attributes];
为名为<relative-time>
的标签定义一个样式,该样式使用此字体并具有此颜色
[[MTStringParser sharedParser] addStyleWithTagName:@"relative-time"
font:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]
color:[UIColor colorWithRed:215.0/255.0 green:0 blue:0 alpha:1]];
并轻松添加另一个具有字体、颜色、背景色并下划线的标签
[[MTStringParser sharedparser] addStyleWithTagName:@"em"
font:[UIFont systemFontOfSize:14]
color:[UIColor whiteColor]
backgroundColor:[UIColor blackColor]
strikethrough:NO
underline:YES];
现在使用您已定义样式的标签编写标记
NSString *markup = [NSString stringWithFormat:@"You can have a <em>complex<em> string that \
uses <em>tags</em> to define where you want <em>styles</em> to be defined. You needed \
this <relative-time>%@</relative-time>.", timeAgo];
然后,爆炸,您的属性字符串
NSAttributedString *attributedString = [[MTStringParser sharedParser] attributedStringFromMarkup:markup];
在提交拉取请求之前,请更新并运行测试。谢谢。