当前位置: 首页 > 编程日记 > 正文

理解NSAttributedString

An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string.

这句话就是对这个类的一个最简明扼要的概括。NSAttributedString管理一个字符串,以及与该字符串中的单个字符或某些范围的字符串相关的属性。比如这个字符串“北京天安门”,“我”跟其他字符的颜色不一样,而“北京”与其他的字体和大小不一样,等等。NSAttributedString就是用来存储这些信息的,具体实现时,NSAttributedString维护了一个NSString,用来保存最原始的字符串,另有一个NSDictionary用来保存各个子串/字符的属性。

Create Attributed String

有3种方法创建Attributed String。

1. 使用initWithString:, initWithString:attributes:, 或者 initWithAttributedString: ,下面是一个实例代码:

NSFont *font = [NSFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:fontforKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil"attributes:attrsDictionary];

可以看到上面创建的整个字符串关联了Font属性。如果希望只是对某一范围的字符串施加某个属性应该使用NSMutableAttributedString的 setAttributes:range:方法。这里例子是使用了Font属性,在Appkit中特殊定义了若干属性,这些属性被用于Core Text中。其他的属性包括前景色、背景色、是否有shadow等,具体可见本文。

2. 使用initWithRTF:documentAttributes:, initWithRTFD:documentAttributes:, and initWithRTFDFileWrapper:documentAttributes:从rich text (RTF) 或者 rich text with attachments (RTFD) 数据中创建。

NSData *rtfData = ...;  // assume rtfData is an NSData object containing valid RTF data
NSDictionary *docAttributes;
NSSize paperSize;NSAttributedString *attrString;if ((attrString = [[NSAttributedString alloc]initWithRTF: rtfData documentAttributes: &docAttributes])) {NSValue *value = [docAttrs objectForKey:@"PaperSize"];paperSize = [value sizeValue];// implementation continues...

3. 使用initWithHTML:documentAttributes: 和 initWithHTML:baseURL:documentAttributes:从HTML数据中创建。有线程安全问题,使用时需要注意。

对RTF和HTML的支持都是AppKit对NSAttributedString的扩展。

Accessing Attributes

从上面对这个类的介绍可以知道,如果我们要访问某个子串/字符的属性,需要提供子串的位置和属性的名字,而如果不提供属性名字,那就把所有属性都返回。下面就是其对应的APIs:

attributesAtIndex:effectiveRange:
attributesAtIndex:longestEffectiveRange:inRange:
attribute:atIndex:effectiveRange:
attribute:atIndex:longestEffectiveRange:inRange:
fontAttributesInRange:
rulerAttributesInRange:

fontAttributesInRange: 和 rulerAttributesInRange: 是由AppKit扩展的属性。

The first four methods also return by reference the effective range and the longest effective range of the attributes. These ranges allow you to determine the extent of attributes. Conceptually, each character in an attributed string has its own collection of attributes; however, it’s often useful to know when the attributes and values are the same over a series of characters. This allows a routine to progress through an attributed string in chunks larger than a single character. In retrieving the effective range, an attributed string simply looks up information in its attribute mapping, essentially the dictionary of attributes that apply at the index requested. In retrieving the longest effective range, the attributed string continues checking characters past this basic range as long as the attribute values are the same. This extra comparison increases the execution time for these methods but guarantees a precise maximal range for the attributes requested.

Methods that return an effective range by reference are not guaranteed to return the maximal range to which the attribute(s) apply; they are merely guaranteed to return some range over which they apply. In practice they will return whatever range is readily available from the attributed string's internal storage mechanisms, which may depend on the implementation and on the precise history of modifications to the attributed string.

那些用reference返回有效范围的方法并不保证一定返回attribute应用的最大范围。它们只保证返回那些attribute有效的一些范围。实际上,它们只是返回attributed string中容易返回的那些信息,是否容易与内部实现,已经对attributed string的精确修改历史有关。

Methods that return a longest effective range by reference, on the other hand, are guaranteed to return the longest range containing the specified index to which the attribute(s) in question apply (constrained by the value of the argument passed in forinRange:). For efficiency, it is important that the inRange: argument should be as small as appropriate for the range of interest to the client.

那些返回最长有效范围的方法时能够保证返回制定attribute有效的最长的range的。为了效率,inRange: 参数应该尽量小,能满足客户需要就好。

When you iterate over an attributed string by attribute ranges, either sort of method may be appropriate depending on the situation. If there is some processing to be done for each range, and you know that the full range for a given attribute is going to have to be handled eventually, it may be more efficient to use the longest-effective-range variant, so as not to have to handle the range in pieces. However, you should use the longest-effective-range methods with caution, because the longest effective range could be quite long—potentially the entire length of the document, if the inRange: argument is not constrained.

Changing an Attributed String

NSMutableAttributedString提供若干方法,即可以修改字符串,又可以修改字符串的属性。经过多次修改后,有些信息可能变的不一致了,为了让信息保持一致,可以使用下面的方法:

fixAttributesInRange:
fixAttachmentAttributeInRange:
fixFontAttributeInRange:
fixParagraphStyleAttributeInRange:
beginEditing
endEditing

这些方法都是AppKit的扩展功能。

Reference:

1. https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/AttributedStrings/AttributedStrings.html#//apple_ref/doc/uid/10000036-BBCCGDBG

2. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAttributedString_AppKitAdditions/Reference/Reference.html#//apple_ref/doc/uid/20000167-BAJJCCFC

转载于:https://www.cnblogs.com/whyandinside/p/3493475.html

相关文章:

Redis集群两种配置方式

2019独角兽企业重金招聘Python工程师标准>>> 第一种使用&#xff1a;JedisCluster <bean id"jedisPoolConfig" class"redis.clients.jedis.JedisPoolConfig"><property name"maxTotal" value"30" /><proper…

调用API弹出打印机属性对话框

调用api弹出打印机属性对话框 Author:vitoriatangFrom:Internet.NET Framework封装了很多关于打印的对话框&#xff0c;比如说PrintDialog, PageSetupDialog. 但是有的时候我们还需要关心打印机属性对话框&#xff0c;那么就可以调用API来解决这个问题。有几个API函数与之相关P…

Oracle DBA学习互联网化的内容

搞了多年的Oracle数据库维护&#xff0c;近几年来&#xff0c;个人感觉基本都在舒适区&#xff0c;技术上没啥进步。而且由于个人资料或者学习方法的限制&#xff0c;Oracle数据库技术上再想精进感觉事倍功半。2013年开始&#xff0c;去IOE的声势搞得轰轰烈烈&#xff0c;mysql…

离不开深度学习的自动驾驶

作者 | 小白来源 | 小白学视觉头图 | 下载于视觉中国深度学习在整个自动驾驶技术的各个部分中进行了应用&#xff0c;例如在感知&#xff0c;预测和计划中都有应用。同时&#xff0c;深度学习也可以用于制图&#xff0c;这是高级自动驾驶的关键组成部分。拥有准确的地图对于自动…

IOS -- base64编码

在iOS7以后可以用NSData自带的base64EncodedStringWithOptions进行编解码&#xff1a; 方法如下&#xff1a; - (NSString *)encodeToBase64String:(UIImage *)image {return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64Charact…

OpenCV持久化(二)

如何利用OpenCV持久化自己的数据结构&#xff1f;我们来看看OpenCV中的一个例子。 MyData.hpp定义自己的数据结构MyData如下: #ifndef MYDATA_HPP #define MYDATA_HPP#include <opencv2/core/core.hpp> #include <iostream> #include <string>using namespac…

Excel、Exchange和C#

摘要&#xff1a;Eric Gunnerson 将向您介绍如何使用 Outlook、Excel 和 C# 创建自定义的日历&#xff0c;该日历可以提供适用于短期项目和长期项目的清晰明了的版式。 下载 csharp05152003_sample.exe 示例文件&#xff08;英文&#xff09;。 虽然一月份已经过去了&#x…

这个宝藏工具,给你一种黑客般的感觉

明天要交作业了&#xff0c;吴检正在宿舍熬夜爆肝拼命敲代码&#xff0c;劈里啪啦的键盘声和咔咔的鼠标声格外嘈杂&#xff0c;室友陈琛瞥了一眼&#xff0c;背过身&#xff0c;沉沉睡去&#xff0c;留下他一人在深夜无尽的黑暗中&#xff0c;断断续续却又没有尽头的咔咔声中凌…

LSTM神经网络

LSTM是什么 LSTM即Long Short Memory Network&#xff0c;长短时记忆网络。它其实是属于RNN的一种变种&#xff0c;可以说它是为了克服RNN无法很好处理远距离依赖而提出的。 我们说RNN不能处理距离较远的序列是因为训练时很有可能会出现梯度消失&#xff0c;即通过下面的公式训…

用C#实现在PowerPoint文档中搜索文本

用编程的方式根据对象模型很容易实现在Word、Excel文档中搜索文本&#xff0c;在PowerPoint里面也同样如此&#xff0c;使用对象模型有助于我们了解office的文档结构。 搜索的思路和方法基本是一样的&#xff0c;用PowerPoint应用程序对象打开指定的文档&#xff0c;用文档对象…

雷军的最后一次 重 大 创 业

这是我人生最后一次重大创业项目。我愿意押上人生全部的声誉&#xff0c;亲自带队&#xff0c;为小米汽车而战&#xff01;——雷军作者 | Carol头图 | 下载于视觉中国出品 | CSDN&#xff08;ID&#xff1a;CSDNnews&#xff09;3月29日19:30&#xff0c;小米春季新品发布会拉…

shell之冒号的作用

冒号&#xff1a; &#xff1a;在shell中是一种命令&#xff0c;意思是总是为真&#xff0c;但是却不做任何操作&#xff0c;即总是为真的空命令eg:[rootlocalhost ~]# ${abc:t1}-bash: t1: command not found[rootlocalhost ~]# : ${abc:t1}[rootlocalhost ~]# echo $abct1[ro…

关于epel源的配置

EPEL&#xff0c;即Extra Packages for Enterprise Linux&#xff0c;这个软件仓库里有很多非常常用的软件,而且是专门针对RHEL设计的&#xff0c;对RHEL标准yum源是一个很好的补充&#xff0c;完全免费使用&#xff0c;由Fedora项目维护&#xff0c;所以如果你使用的是RHEL&am…

C#如何在Form中嵌入并且操作Excel表格

网上比较多讲述如何操作excel表的文章&#xff0c;但都是启动excel的窗口来打开excel数据文件。有时候需要把excel表嵌入到自己程序的form中&#xff0c;给客户一个不用切换窗口的操作界面&#xff0c;似乎更好。这在vc中用ole技术很容易实现&#xff0c;但是在c#中方法就不一样…

自研芯片架构 ,这家中国公司发布DPU芯片计划

近日,专注于智能计算领域的DPU芯片和解决方案公司中科驭数发布了其下一代DPU芯片计划&#xff0c;将基于自研的KPU&#xff08;Kernel Processing Unit&#xff09;芯片架构&#xff0c;围绕网络协议处理、数据库和大数据处理加速、存储运算、安全加密运算等核心功能&#xff0…

QQ超时不能刷新好友接收发送信息

如果您在其它电脑登录时正常&#xff0c;只在本地出现此种情况&#xff0c;可能与您本机的设置及网络限制有关&#xff0c;建议您先确保安装的是我司的官方版本&#xff0c;然后再搜索并删除您的QQ号码文件夹&#xff08;会丢失聊天记录&#xff0c;请注意备份&#xff09;&…

JavaStuNote 4

装箱(inbox)和拆箱(outbox) 代表了类类型和基本类型之间的转换行为。 手动版本号&#xff1a; Integer b new Integer(10); Int a b.intValue; 自己主动版本号&#xff1a; Integer b30; Integer bnew Integer(30); Int ab; int a b.intValue(); 由于基本类型…

把Doc文档转换成HTML等其它格式

利用microsoft Word 9.0 Object Library可以在页面中对Doc文档进行格式转换。有关Word对象的一些方法可以参考Open和Save。下面是进行转换的代码[C#]&#xff1a; /// <summary>/// WordToHtml 的摘要说明。/// 首先要添加引用&#xff1a;Microsoft Word 9.0 Object Li…

如何学好Python?相信很多人都做错了!

Python入门从哪开始&#xff0c;以我的过往经验&#xff0c;发现很多的教程都是这样讲的&#xff1a;先介绍 Python 的基本语法规则、list、dict、tuple 等数据结构&#xff0c;然后再介绍字符串处理和正则表达式&#xff0c;介绍文件等IO操作.... 就这样一点一点往下说。然而这…

艾麦捷科技-铂金小猪新年致辞

2019独角兽企业重金招聘Python工程师标准>>> 光阴似箭&#xff0c;2013年是匆忙的一年&#xff0c;艾麦捷科技从最初的“笑谈”到现在上线&#xff0c;招财猪进销存管理软件从无到有&#xff0c;到现在多次更新&#xff0c;无一不是在匆忙中完成的&#xff0c;尽管很…

C#开源框架整理

Json.NET http://json.codeplex.com/ Json.Net 是一个读写Json效率比较高的.Net框架.Json.Net 使得在.Net环境下使用Json更加简单。通过Linq To JSON可以快速的读写Json&#xff0c;通过JsonSerializer可以序列化你的.Net对象。让你轻松实现.Net中所有类型(对象,基本数据类型 …

提供一个基于.NET的加密/解密算法

提供一个基于.NET SymmetricAlgorithm 类的、带私钥的加密/解密算法的包装类。使用方法&#xff1a; symmcrypto de new SymmCrypto(SymmCrypto.SymmProvEnum.DES);Response.Write(x.Decrypting(de.Encrypting("ok","yyy"),"yyy")); 类的实现…

ubuntu修改IP

一、使用命令设置Ubuntu的ip地址1. 设置IP sudo ifconfig eth0 203.171.239.155 netmask 255.255.255.224 这样就算设置好了网卡eth0的IP地址和子网掩码2. 设置网关 sudo route add default gw 203.171.239.1293. 设置DNS 修改/etc/resolv.conf&#xff0c;在其中加入 nameserv…

Arm 十年重磅发布 v9 架构,不受 EAR 约束,未来将覆盖 3000 亿颗芯片

整理 | 伍杏玲出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;随着 AI、大数据、IoT 技术的相互渗透&#xff0c;人们对数据的要求也越来越高&#xff0c;如何提供普适专用、安全而强大的处理能力的架构&#xff1f;Arm 为这个答案准备十年。近日&#xff0c;Arm 推出…

HDU 6051 - If the starlight never fade | 2017 Multi-University Training Contest 2

/* HDU 6051 - If the starlight never fade [ 原根,欧拉函数 ] | 2017 Multi-University Training Contest 2 题意&#xff1a;给定 m,p, p 是素数设 f(i) 是 满足 (xy)^i ≡ x^i mod p 的 (x,y) 对数 且 1 ≤ x ≤ p-1 , 1 ≤ y ≤ m 求 ∑[1≤i≤p-1] i*f(i)限制&#xff…

干货!用 Python 快速构建神经网络

作者 | ZackSock责编 | 欧阳姝黎头图 | 下载于视觉中国前言机器学习一直是Python的一大热门方向&#xff0c;其中由神经网络算法衍生出来的深度学习在很多方面大放光彩。那神经网络到底是个个什么东西呢&#xff1f;说到神经网络很容易让人们联想到生物学中的神经网络&#xff…

才知道百度也提供了智能DNS服务 - 加速乐

http://jiasule.baidu.com/ 智能DNS 依托百度多年积累的高精度DNS识别库&#xff0c;平均只需5秒全球DNS服务器全部生效&#xff0c;百度蜘蛛1秒生效。抗攻击、无限解析记录&#xff0c;免费支持电信、联通、移动、铁通、教育网、国外、搜索引擎等分线路解析。 极致云加速 百度…

c#中结构与类的区别

类与结构的差别如何选择结构还是类一&#xff0e;类与结构的示例比较&#xff1a;结构示例&#xff1a;public struct Person {string Name;int height;int weightpublic bool overWeight(){//implement something}}类示例&#xff1a;public class TestTime {int hours;int mi…

Samba amp; Nginx - Resource temporarily unavailable

先说说本人的开发环境&#xff1a;Win7 Editplus VMware(CentosSambaNginx)。用Samba在Centos上把web文件夹(如www)共享&#xff0c;然后在Win7上訪问这个文件夹。之所以这么用的原因有&#xff1a; 习惯了Windows。效率比較高Editplus编辑器好用&#xff0c;相对于vi系列来说…

好多Javascript日期选择器呀-7

the Coolest DHTML Calendar 最特別的在於按下月份跟年份的加減按鈕不放&#xff0c;就可以選擇該項目。但實際上按著左鍵拖曳實在是一件很累的事&#xff0c;而且不懂電腦的 End-user 根本就不知道要按著不放&#xff0c;還得特地花時間去說明真的吃力不討好。 正好這次的專案…