NTAttributedStringBuilder 1.02

NTAttributedStringBuilder 1.02

测试已测试
语言语言 Obj-CObjective C
许可证 MIT
发布日期最后发布日期2015年11月

Ethan Nagel维护。



  • 作者
  • Ethan Nagel

这是一个快速、灵活且易于使用,构建格式化字符串的系统,而无需依赖嵌入的 HTML。

NSMutableAttributedString 在构建格式化字符串时非常繁琐且容易出错。最常见的方法是通过解析一些类型的 html 或 markdown 来创建 AttributedString。尽管这种方法可行,但它们将命令嵌入到字符串中,导致您需要重复运行应用程序以检查语法是否正确。此外,在创建字符串时,您不会从 Xcode 的自动完成功能中获得任何帮助。

NTAttributedStringbuilder 采用不同的方法。它维护一个当前属性字典,这些属性在文本追加时应用到文本上。通过以有趣的方式更改属性,可以构建非常复杂的属性字符串。

这里包含了一些示例。类有良好的文档,并启用了“快速帮助”。

使用 NTAttributedStringBuilder 属性

几乎任何属性都可以作为属性设置。不仅暴露了高级属性,还将嵌套属性,例如在追加文本时使用的属性,设置为其当前值。以下是一个简单的示例

NTAttributedStringBuilder *b = [[NTAttributedStringBuilder alloc] init];

b.firstLineHeadIndent = 20;
b.paragraphSpacing = 10.0;
b.lineSpacing = 5.0;
b.font = [UIFont fontWithName:@"Avenir-LightOblique" size:12.0];

[b append:someText];

self.label.attributedString = b.attributedString;

追加 NTAttr(和其他)属性

此外,可以通过传递值到 append 方法来设置属性。Append 处理几个特殊对象

  • NSArray - 在数组内容中递归展开。这是一种创建“样式”——其他设置的数组的绝佳方式。
  • NSDictionary - 字典的内容作为属性应用。键是属性名称。值是要设置的属性值或 NSNull 以清除属性。
  • NSString - 使用当前属性追加字符串。
  • id<NTAttributedStringBuilderElement> 实现此协议的任何对象负责追加其自己的输出。
  • NTAttr 方法。这些方法返回用于设置任何属性的对象,例如行间距或下划线。
  • UIFont - 将当前字体设置为传递的值。
  • UIColor - 设置前景色为传递的值。
  • NSParagraphSettings - 使用传递的值设置所有段落设置。

append 函数允许组合复杂格式

NSArray *names = @[@"Ethan", @"Tom", @"Scott"];

NTAttributedStringBuilder *b = [[NTAttributedStringBuilder alloc] init];

NSArray *nameStyle = @[[NTAttr push], [UIColor redColor], [NTAttr fontName:@"Avenir-Heavy"], [NTAttr underlineStyle:NSUnderlineStyleSingle]];
NSArray *endNameStyle = @[[NTAttr pop]];

b.font = [UIFont fontWithName:@"Avenir-Medium" size:18.0];

[b appendFormat:@"Here is a list of %d names: ", names.count];

for(int index=0; index<names.count; index++)
{
    if ( index > 0 )
        [b append:@", "];

    [b append:@[nameStyle, names[index], endNameStyle]];
}

[b append:@"."];

self.label.attributedString = b.attributedString;

安装

如果您正在使用 Cocoapods,请在 podfile 中添加 'pod NTAttributedStringBuilder'。如果您采用传统方法,将 .m 和 .h 文件复制到您的项目中即可享受使用!(