MTStringAttributes 0.1.0

MTStringAttributes 0.1.0

测试已测试
Lang语言 Obj-CObjective C
许可证 MIT
Released最后发布2014年12月

Adam Kirk维护。



  • 作者
  • Adam Kirk

创建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];

贡献

在提交拉取请求之前,请更新并运行测试。谢谢。

作者

Adam Kirk (@atomkirk)