1

正如我从 Apple 文档的 UITextView 的属性文本属性中了解到的那样:

此属性默认为 nil。为该属性分配一个新值也会用相同的字符串数据替换 text 属性的值,尽管没有任何格式信息。此外,分配新的 a 值会更新 font、textColor 和 textAlignment 属性中的值,以便它们反映从属性字符串中位置 0 开始的样式信息。

因此,我无法通过在不同位置具有多个属性的代码添加属性字符串。

有人可以帮我在iOS6中通过代码创建以下效果吗?这可以使用 nib 文件并通过更改 UITextView 中文本部分的范围属性来实现,但我似乎无法通过代码重现效果。

<'font systemFontOfSize=18>想要的</font>效果<'textColor = [UIColor redColor]>写成 b </textColor> y 代码

假设标签对应于属性。

PS 我不想使用 CATextLayers,因为我正在尝试将 AutoLayout 功能与 UITextView 一起使用。

4

1 回答 1

4

您可以使用包含您需要的所有属性的 NSDictionary 构建 NSAttributedString:

NSAttributedString* attString = [[NSAttributedString alloc] 
               initWithString: @"Desired effect to be written by code" 
                   attributes: (NSDictionary*)attributes];

或者使用它的可变子类 NSMutableAttributedString:

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]  
               initWithString: @"Desired effect to be written by code"];

    [attString addAttribute: NSForegroundColorAttributeName 
                      value: [UIColor redColor] 
                      range: NSMakeRange(15,15)];

......
然后......

myTextView.attributedText = attString;

每个属性都应用于字符串的一个 NSRange(位置、长度)。不同的属性类型(例如颜色、字体大小)可以重叠不同的范围。

更新
使用 NSMutableAttributedString 示例。NSAttributedString's initWithString:attributes将在字符串的整个范围内应用属性,这是您要避免的,抱歉造成混淆。

于 2012-12-18T12:28:08.837 回答