[翻译] WPAttributedMarkup

WPAttributedMarkup

https://github.com/nigelgrange/WPAttributedMarkup

WPAttributedMarkup is a simple utility category that can be used to easily create an attributed string from text with markup tags and a style dictionary.

WPAttributedMarkup是一个简单而实用的category,你可以很方便的来用他来创建富文本,通过用标签的方式,还有属性字典的方式.

The category allows you to turn text such as:

这个category允许你用以下的方式来设置富文本:

<bold>Bold</bold> text

into "Bold" text by using a style dictionary such as:

转换到"粗体",你可以用以下的属性字典:

  NSAttributedString *as = [@"<bold>Bold</bold" attributedStringWithStyleBook:@{@"body":[UIFont fontWithName:@"HelveticaNeue" size:18.0],
  @"bold":[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0]}];

In this example, the style associated with "body" is applied to the whole text, whereas the style associated with "bold" is applied to the text contained within < bold > tags.

在这个例子中,与"body"相关的样式,<bold>*****</bold的*****都被设置成了字体对应的样式.

All tags (with the exception of ‘body‘) are user-defined.

所有的标签都是用户事先定义好的.

The dictionary is called a ‘style book‘ as the intention is for it to contain all of the application fonts, colours etc in a single place.

这个字典文件被称作"样式书",里面包含了程序的自提,颜色等属性诸如此类的设置.

FAQ

Q. Can this convert html to styled text?

问:这个可以讲html转换成富文本么?

A. In general, no. The syntax is html-like, but all tags are user-defined. If the html is correctly formatted, and uses a strict set of tags, you could convert html to attributed text by defining an appropriate set of tags (b, h1, h2, etc).

答:大体上,不行.也许这个格式看起来像html风格的标签,但是,这些都是用户自定义.如果html是标准格式的,或者说是用了个严谨的完整的标签格式,你可以通过自定义标签的方式来将html转换成富文本.

Q. Doesn‘t NSAttributedString already convert html text using something like:

问:富文本不是本身就支持将网页转换么?

[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                             options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                       NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                  documentAttributes:nil error:nil];

A. It does. However, the above approach is very slow (it uses a WebView in the background) and runs asynchronously (just try creating one in a UITableViewCell and scroll the table too fast...).

In addition, any styles must be set in the document css, rather than being able to pass in standard colour and font classes that your application already uses.

答:富文本确实本身就支持直接的html转换,但是,上面的转换非常的缓慢.(它在后台使用了WebView来转化),并且是异步执行的(你在tableView上滑动时候就知道那玩意有多慢了.....).

What styles are supported?

The following objects can be used in the style dictionary:

以下的这些属性可以被设置到属性字典当中:

UIColor : For colouring a section of text. 给文本设置颜色

@"red": [UIColor redColor]

UIFont : For setting the font for a section of text. 给文本设置字体

@"bold":[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0]

NSDictionary : Applies an attributed string style key/pair to the section of text. This can be used for applying underline, strikethrough, paragraph styles, etc as well as custom attributes. 根据键值对给文本设置属性.这个可以用来设置下划线,中划线,段落样式等.

@"u": @{NSUnderlineStyleAttributeName : @(kCTUnderlineStyleSingle|kCTUnderlinePatternSolid)}

NSArray : An array of any style items, all of which are applied to the section of text. 一个用来设置样式的数组,里面由小样式组成.

@"u": @[[UIColor blueColor],
@{NSUnderlineStyleAttributeName : @(kCTUnderlineStyleSingle|kCTUnderlinePatternSolid)} ]

NSString : Applies a named style to the section of text. Useful for applying an existing style in addition to some new attributes without needing to copy the existing attributes.

 @"red": [UIColor redColor],
 @"redunderline": @[ @{NSUnderlineStyleAttributeName : @(kCTUnderlineStyleSingle|kCTUnderlinePatternSolid)}, @"red" ]

UIImage : Inserts the UIImage into the text at the section of text. Note: The text inside the image tags must contain only a single character, which will be replaced by the image. 插入一张图片

@"thumb":[UIImage imageNamed:@"thumbIcon"]

Used in the text as:

 <thumb> </thumb>

Extras

Some extra utility classes are included which may also be of use in association with WPAttributedMarkup. In particular, the WPHotspotLabel class can be used to apply block methods to any part of the attributed string, allowing trivial application-specific links to be created.

还有些额外的很实用的类,可以和WPAttributedMarkup配合使用.WPHotspotLabel 可以用来接受block方法方法,用来设置富文本.

WPAttributedStyleAction - A class which wraps a block and allows insertion into an attributed string using the styledAction method. This actually adds a link style to the text, so the text will also inherit the attributed defined in the link style, if defined.

WPAttributedStyleAction 给文本添加了超链接属性,如果定义了的话.

This can be used as follows:

@"help":[WPAttributedStyleAction styledActionWithAction:^{
                             NSLog(@"Help action");
                         }]

WPTappableLabel - A simple UILabel subclass which allows an onTap block to be set, which is called when the label is tapped.

WPTappableLabel 一个简单的UILabel的子类,允许你设置点击事件.

WPHotspotLabel - A subclass of WPTappableLabel which detects the attributes of the text at the tapped position, and executes the action if a WPAttributedStyleAction attribute is found.

WPHotspotLabel 是WPTappableLabel 的子类,用以检查属性点击区域,以及执行点击事件,如果设置了点击事件的话.

Note that these classes have not been tested as exhaustively, so it is possible that these do not behave as expected under all conditions. In particular, WPHotspotLabel uses CoreText layout to detect the attributes of the tapped position, which could potentially result in different layout than the one being displayed. Under all tests performed so far with simple labels and formatting, the detection does work correctly, but you have been warned!

注意,这些类并没有经过完整的测试,所以,有时候某些类并不能达到你想要的效果.WPHotspotLabel是使用了CoreText的自动布局来检测属性点击的区域,这个也许会在不同的布局当中显示异常.目前所进行的所有测试当中,包括了文本的格式相关的都没有什么问题.当点击事件区域的检测也许会出现异常,这里已经给你提醒了哦!

Example

// Example using fonts and colours
NSDictionary* style1 = @{@"body":[UIFont fontWithName:@"HelveticaNeue" size:18.0],
                         @"bold":[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0],
                         @"red": [UIColor redColor]};

 // Example using arrays of styles, dictionary attributes for underlining and image styles

 NSDictionary* style2 = @{@"body" :
                             @[[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0],
                               [UIColor darkGrayColor]],
                            @"u": @[[UIColor blueColor],
                                @{NSUnderlineStyleAttributeName : @(kCTUnderlineStyleSingle|kCTUnderlinePatternSolid)}
                                 ],
                            @"thumb":[UIImage imageNamed:@"thumbIcon"] };

// Example using blocks for actions when text is tapped. Uses the ‘link‘ attribute to style the links

NSDictionary* style3 = @{@"body":[UIFont fontWithName:@"HelveticaNeue" size:22.0],
                         @"help":[WPAttributedStyleAction styledActionWithAction:^{
                             NSLog(@"Help action");
                         }],
                         @"settings":[WPAttributedStyleAction styledActionWithAction:^{
                             NSLog(@"Settings action");
                         }],
                         @"link": [UIColor orangeColor]};

self.label1.attributedText = [@"Attributed <bold>Bold</bold> <red>Red</red> text" attributedStringWithStyleBook:style1];

self.label2.attributedText = [@"<thumb> </thumb> Multiple <u>styles</u> text <thumb> </thumb>" attributedStringWithStyleBook:style2];

self.label3.attributedText = [@"Tap <help>here</help> to show help or <settings>here</settings> to show settings" attributedStringWithStyleBook:style3];

How it works

The utility consists of two categories:

实用功能包含了以下两个category:

NSMutableString+TagReplace : Used internally to strip all tags out of a NSMutableString, building an array of tags with start and end ranges.

进行tag值的替换类.

NSString+WPAttributedMarkup : Contains a single public method:

-(NSAttributedString*)attributedStringWithStyleBook:(NSDictionary*)styleBook;

This builds an arrange of tags using NSMutableString+TagReplace, then iterates through each of the tags and applies the styles found in the style book.

If no style is found for a tag, then the tag is simply stripped from the string with no style applied.

If the body tag is found in the style book, then this is applied to the entire string before any other styles are applied.

时间: 2024-12-10 17:31:09

[翻译] WPAttributedMarkup的相关文章

在GlassFish应用服务器上创建并运行你的第一个Restful Web Service【翻译】

前言 本人一直开发Android应用,目前Android就业形势恶劣,甚至会一路下滑,因此决定学习服务器开发.采用的语言是java,IDE是Intellij,在下载Intellij的同时看到官网很多优秀的guide文章,于是按照guide成功完成了一个RESTful的demo.官方文档非常简洁,给我带来了很大的帮助,于是翻译之,希望对其他不愿意看原文的人有所帮助.由于水平有限,读者发现错误请指正,谢谢. 原文地址: https://www.jetbrains.com/help/idea/2016

Java 7 Concurrency Cookbook 翻译 序言

在日常的Java代码开发过程中,很难免地有对多线程的需求,掌握java多线程和并发的机制也是Java程序员写出更健壮和高效代码的基础.笔者找寻国内已出版的关于Java多线程和并发的的中文书籍和翻译书籍,大家一致推荐的是<Java Concurrency in Practice>,笔者暂时还没有看英文原版,笔者看的是它的翻译版<Java并发编程实战>,笔者读起来感觉并不通畅,不知道是翻译的问题还是原版本来就写得不够流畅,同时感觉知识的深度也超过了入门的需求. 笔者在机缘巧合之下,发现

[翻译] ORMLite document -- How to Use Part (二)

前言 此文档翻译于第一次学习 ORMLite 框架,如果发现当中有什么不对的地方,请指正.若翻译与原文档出现任何的不相符,请以原文档为准.原则上建议学习原英文文档. ---------------------------------------------------------------------------------------------- 二.如何使用 2.7 表的创建 ORMLite 提供了一些工具类为您存储在数据库中的类创建 table 和 schema. 2.7.1 Tabl

Reveal常用技巧(翻译来自Reveal官网blog)

翻译来自官网:http://revealapp.com/blog/reveal-common-tips-cn.html 以下基于Reveal 1.6. 用于快速上手的内置应用 刚刚下载Reveal,啥都还没配置呢,想先随便玩玩看,怎么办? 我们花了不少时间开发这个复杂程度类似与实际场景的Sample应用──Soundstagram(音频分享版的Instagram, ¯\_(ツ)_/¯),就是为了让大家能最快速地上手Reveal,尝试它的各种强大功能. 在 Help 菜单项中,点击 Inspect

qt 国际化(翻译时会触发changeEvent)

1. 修改工程文件 .pro ,加入翻译源文件 hello_world.ts: TRANSLATIONS += \        Resource/translations/hello_world.ts 写代码时需要注意下面两点:  2. 源码用 utf-8 字符集3. 源码中需要翻译的字符串必须用英文(不能有中文或其它语言),则需要用 tr()  函数.  例如: QMessageBox::information(this,tr("Information"),tr("Hel

还在吐槽翻译的外版书质量差吗?谈谈我个人的理解

很难想象哪个学习计算机技术的人是没看过这方面书籍的,如果只是在网上看看技术贴,那样得来的知识绝对是离散的,不系统的.而要真正学好一门学问(比如一门计算机语言或者一门技术),一本好书的作用是不言而喻的.很多人抱怨国人在技术图书方面抄来抄去,不求甚解,虽然出版图书者甚众,但最终成为精品者却凤毛麟角.于是,更多读者热衷于外版书.但显然,并非所有国人的外语水平都足以在阅读原版书籍时毫无障碍.那么退而求其次,寻求翻译版就成为一种看似不得已的选择. 不幸的是,网上对于翻译版书籍的吐槽可以说从未消停.我也看过

VLD 1.0 ReadMe翻译尝试

近期想学习下VLD的实现,打算从最简单的V1.0版本看起.以下是V1.0版本自己尝试翻译下,最新的2.x版本似乎强大了很多. 简介 Visual C++提供了内置的内存检测机制,但其充其量只满足了最小定位需求.VLD工具定位为内置内存泄漏的替代,提供了如下特性: 泄漏内存块的全调用栈回溯,包括文件及其行号: 泄漏内存完整转储(hex和ascii格式): 可定制的泄漏报告等级(报告的详细程度可配置) 相对于Purify和BoundsChecher工具其是免费的,而其他免费工具,往往需要入侵式代码.

如何调用有道翻译API(Java,HTTP)

申请Key 首先如图进入有道翻译,在下方点击"有道翻译API". 紧接着来调用数据接口,按提示完成下列输入框. 如下图所示,已经申请成功了. 下图是官方给的示例,可以有xml和json.jsonp等三种数据格式. 代码(Java) public class TestPost { public static void main(String[] args) { new ReadByPost().start(); } } class ReadByPost extends Thread{ @

Android studio project文件结构翻译

Android studio project文件结构翻译 个人翻译,用作备忘. 链接地址:https://developer.android.com/tools/projects/index.html#ApplicationModules Android Project Files Studio的项目文件和设置,设置的作用范围包含所有的module. 以以下的demo为例. .git:git版本控制的文件存放目录. .gradle:gradle执行一些编译所生成的目录 Idea: 由Intell