Skip to content

NSAttributedString ​

NSAttributedString 表示一段带样式的文字,称为富文本:一个字符串,加上每一段上的一组属性。属性规定这一段用什么字体、什么颜色、有没有下划线、字距多大。同一个字符串里不同的段可以有不同的属性,所以一行文字里可以混用几种字号和颜色。

NSAttributedString 建好之后内容不能改。要给某一段加属性、拼接、换文字,用它的子类 NSMutableAttributedString。

富文本自己不显示。把它交给标签、输入框、按钮,由它们显示:

显示在哪写法
UILabellabel.attributedText = text
UITextFieldfield.attributedText = text、field.attributedPlaceholder = text
UITextViewtextView.attributedText = text
UIButtonbutton.setAttributedTitle(text, { forState: ['normal'] })

和富文本一起用的几个类:

类是什么
NSMutableAttributedString可以改的富文本
NSParagraphStyle段落样式:对齐、行距、段距、缩进。属性只读
NSMutableParagraphStyle可以改的段落样式
NSShadow文字的阴影
NSTextAttachment附件:在一个字符的位置上显示一张图片

注意:这一组类的读写行为(建富文本、读写属性、改内容、量尺寸、四种视图上的读写)在模拟器的验收里运行过(iPhone Air,iOS 27.2)。屏幕上显示成什么样没有核对:各处「效果」里标着未在模拟器验证的,说的都是画面,依据是 Apple 的头文件和文档。

NSAttributedString 不派发事件。它的内容不会变,所以没有变化通知。

继承关系:EventTarget → NSObject → NSAttributedString

怎么用富文本做混排的价格、下划线、行距、图文混排,见指南显示带样式的文字。

构造函数 ​

NSAttributedString()

创建一段富文本:空的、不带属性的文字、整段用同一组属性的文字,或者照另一个富文本抄一份。

静态方法 ​

NSAttributedString.attributedStringWithAttachment()

创建一个只含一个附件的富文本,长度是 1。用来把图片插进文字里。

实例属性 ​

还继承 NSObject 的属性。

属性说明
string 只读不带属性的文字
length 只读长度,UTF-16 码元的个数

实例方法 ​

还继承 NSObject 的方法。

读属性:

方法说明
attributesAtIndex()某个位置上的全部属性
attribute()某个位置上的一个属性
enumerateAttributesInRange()按「属性相同的连续一段」逐段遍历

取一段、比较:

方法说明
attributedSubstringFromRange()取出一段,属性跟着走
isEqualToAttributedString()文字和每一处的属性是否都相同
containsAttachmentsInRange()一段里有没有附件

量尺寸:

方法说明
size()排成一行需要多大
boundingRectWithSize()限定在一个大小里排需要多大

副本:

方法说明
copy()一份内容相同、不可改的副本
mutableCopy()一份内容相同、可以改的副本

范围怎么写 ​

给某一段加属性时要说明是哪一段,用 NSRange:从第几个位置开始、多长。位置和长度的单位是 UTF-16 码元,和 JS 字符串的下标是同一个单位,所以 '合计 ¥128'.indexOf('¥') 得到的数可以直接用。一个表情符号占两个。

js
const a = new NSRange(3, 4);              // 从下标 3 开始的 4 个码元
const b = { location: 3, length: 4 };     // 写入时也收这种普通对象

范围超出文字的长度时抛 TypeError,报错里带着范围和文字的长度:

TypeError: addAttributes range {8, 9} is out of bounds; the string length is 10

交出去之后再改,界面不会跟着变 ​

视图拿走的是赋值那一刻的内容。之后再改同一个 NSMutableAttributedString,视图上显示的不变,要重新赋值一次。

段落样式和阴影也是这样:放进富文本的是当时的一份副本,之后再改那个 NSMutableParagraphStyle 或 NSShadow,已经建好的富文本不变。

从视图上读回来的富文本(比如 label.attributedText)是一份不可改的快照,每次读可能是不同的对象。比较两个富文本的内容用 isEqualToAttributedString(),不要用 ===。

富文本的属性 ​

写属性时用一个对象,键是属性的名字。读出来也是同样形状的对象,没有的属性不出现在里面。

名字值说明
fontUIFont字体。不带时系统用 12 pt 的 Helvetica
foregroundColor颜色文字颜色。不带时是黑色
backgroundColor颜色文字背后的底色。不带时没有底色
paragraphStyleNSParagraphStyle段落样式,见 NSParagraphStyle
kern数,pt字距调整。正数拉开,负数收紧
tracking数,pt字间距。和 kern 的差别是它会关掉被拉断的连字
ligature整数连字(比如 fi 连成一个字形)。1 用字体默认的连字,0 不用
underlineStyle线型名的数组下划线,取值见线型
underlineColor颜色下划线的颜色。不带时和文字颜色相同
strikethroughStyle线型名的数组删除线,取值见线型
strikethroughColor颜色删除线的颜色。不带时和文字颜色相同
strokeWidth数,字号的百分比描边的粗细。0 不描边;正数只描边、不填充,得到空心字;负数既描边又填充。空心字常用 3
strokeColor颜色描边的颜色。不带时和文字颜色相同
shadowNSShadow阴影
baselineOffset数,pt相对基线上移多少。负数是下移
link字符串链接的地址。写入时也收 URL 对象
attachmentNSTextAttachment这个字符的位置上显示的附件

写属性时的规矩:

  • 值是 undefined 的键视为没带。
  • 名字写错抛 TypeError,报错里列出全部能用的名字:NSAttributedString has no attribute "colour"; expected one of: font / paragraphStyle / …
  • 颜色写错不抛。 认不出的颜色字符串打一条警告,这个键不生效,其他键照常。这和别处写颜色的规矩一样,见 UIColor。颜色的值写 null 会抛:不要这个颜色就不带这个键。
  • 数按数转。 kern: '2' 得到 2;转不成数的抛 TypeError。
  • 字体、段落样式、阴影、附件必须是对应的类,否则抛 TypeError,例如 font must be a UIFont, got "Helvetica"。

读出来的值:颜色是字符串;字体和附件是写进去的那个对象;段落样式和阴影是副本。

线型 ​

underlineStyle 和 strikethroughStyle 的值是数组,三类各选至多一个:

取值效果
'single'一条细线
'thick'一条粗线
'double'两条细线
'patternDot'点线
'patternDash'虚线
'patternDashDot'一划一点交替
'patternDashDotDot'一划两点交替
'byWord'只画在词的下面,空格下面不画

前三个是线型,中间四个是虚线的样式(不写是实线),最后一个可以和前面的任意组合。空数组 [] 表示不画线。

  • 写了两个线型,或者两个虚线样式:TypeError: underlineStyle takes at most one of single / thick / double
  • 写的不是数组:TypeError: underlineStyle must be an array of style names, got "single"
  • 名字不认识:TypeError: underlineStyle has no value "wavy"; expected one of: …

示例 ​

一行价格 ​

从空白 App 开始,在屏幕上显示一行价格:前面是普通的小字,价格是红色大字,原价是灰色带删除线。

js
application.addEventListener('sceneconnect', (e) => {
  const win = new UIWindow(e.scene);
  const page = new UIViewController();
  page.view.backgroundColor = 'systemBackground';
  win.rootViewController = page;
  win.makeKeyAndVisible();

  const text = new NSMutableAttributedString('到手价 ', {
    font: UIFont.systemFontOfSize(15),
    foregroundColor: 'label',
  });
  text.appendAttributedString(new NSAttributedString('¥128', {
    font: UIFont.boldSystemFontOfSize(26),
    foregroundColor: 'systemRed',
  }));
  text.appendAttributedString(new NSAttributedString('  ¥199', {
    font: UIFont.systemFontOfSize(13),
    foregroundColor: 'secondaryLabel',
    strikethroughStyle: ['single'],
  }));

  const label = new UILabel();
  label.attributedText = text;

  label.translatesAutoresizingMaskIntoConstraints = false;
  page.view.addSubview(label);
  NSLayoutConstraint.activateConstraints([
    label.centerXAnchor.constraintEqualToAnchor(page.view.centerXAnchor),
    label.centerYAnchor.constraintEqualToAnchor(page.view.centerYAnchor),
  ]);
});

效果(未在模拟器验证)

  • 屏幕正中出现一行字:「到手价」是 15 pt 的普通字,「¥128」是 26 pt 的红色粗体,「¥199」是 13 pt 的灰色字,中间划着一条线。
  • 三段的底边对齐在同一条基线上。

更多写法见指南显示带样式的文字。

对应的 iOS API ​

ObjCJS
[[NSAttributedString alloc] initWithString:@"x" attributes:@{NSFontAttributeName: font}]new NSAttributedString('x', { font })
[[NSMutableAttributedString alloc] initWithAttributedString:other]new NSMutableAttributedString(other)
NSForegroundColorAttributeName: UIColor.systemRedColorforegroundColor: 'systemRed'
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle | NSUnderlineStylePatternDash)underlineStyle: ['single', 'patternDash']
[text addAttribute:NSKernAttributeName value:@2 range:NSMakeRange(0, 3)]text.addAttribute('kern', { value: 2, range: new NSRange(0, 3) })
[text setAttributes:attrs range:range]text.setAttributes(attrs, { range })
[text removeAttribute:NSKernAttributeName range:range]text.removeAttribute('kern', { range })
[text appendAttributedString:other]text.appendAttributedString(other)
[text insertAttributedString:other atIndex:0]text.insertAttributedString(other, { atIndex: 0 })
[text replaceCharactersInRange:range withString:@"x"]text.replaceCharactersInRange(range, { withString: 'x' })
[text attributesAtIndex:0 effectiveRange:NULL]text.attributesAtIndex(0)
[text attribute:NSFontAttributeName atIndex:0 effectiveRange:NULL]text.attribute('font', { atIndex: 0 })
[text enumerateAttributesInRange:range options:0 usingBlock:^…]text.enumerateAttributesInRange(range, (attributes, range) => { … })
[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin context:nil]text.boundingRectWithSize(size, { options: ['usesLineFragmentOrigin'] })
CGFLOAT_MAXNumber.MAX_VALUE
[NSTextAttachment textAttachmentWithImage:image]NSTextAttachment.textAttachmentWithImage(image)
[NSAttributedString attributedStringWithAttachment:attachment]NSAttributedString.attributedStringWithAttachment(attachment)
style.alignment = NSTextAlignmentCenterstyle.alignment = 'center'
label.attributedText = textlabel.attributedText = text
[button setAttributedTitle:text forState:UIControlStateNormal]button.setAttributedTitle(text, { forState: ['normal'] })

参见 ​