对 NSAttributedString 的一部分应用加粗,同时保留字体大小和字体 [英] Apply bolding to portion of NSAttributedString, while preserving font sizes and faces

查看:76
本文介绍了对 NSAttributedString 的一部分应用加粗,同时保留字体大小和字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 iOS 开发富文本编辑器,使用 UITextViewNSAttributedString.它的功能与传统的类似(即选择一个区域,单击一个按钮,并将该效果应用于该区域,同时保留文本的任何其他属性.

I'm working on a rich text editor for iOS, using a UITextView along with an NSAttributedString. It'll function similarly to traditional ones (i.e. selecting a region, clicking a button, and it applies that effect to that region, while preserving any other attributes on the text.

不幸的是,对于 NSAttributedString,并不是所有的都可以独立调整.其中一些(至少是粗体、字体和字体大小)都需要传递一个 UIFont,它将为该区域设置所有这些属性(即使您只想设置一个).看到单个区域可能包含多个面和尺寸,这将导致这种幼稚的方法破坏了许多现有格式.

Unfortunately with NSAttributedString, not all of them can be adjusted independently. Several of them (at least bold, font face, and font size) all require passing a UIFont, which'll set all of those attributes for the region (even if you only wanted to set one). Seeing as a single region might include several faces and sizes, this'll result in the naive approach breaking a lot of existing formatting.

是否有任何推荐的方法来实现这一点?我想我唯一的选择是遍历我想要应用它的区域的属性,将其分组为具有相同其他字体属性的块,然后将其单独应用于每个块.

Is there any recommended means to accomplish this? I'm thinking my only option will be to iterate through the attributes for the region I want to apply it to, group it into chunks that have the same other font attributes, and then apply it to each chunk individually.

推荐答案

您的想法是正确的,enumerateAttribute:inRange:options:usingBlock: 已经为您提供了算法.要使用它来处理字体运行:

You have the right idea and the algorithm is already provided for you by enumerateAttribute:inRange:options:usingBlock:. To use this to process font runs:

[myAttributedString enumerateAttribute:NSFontAttributeName
                               inRange:selectedRange
                               options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
                            usingBlock:addBoldBlock
]

其中 addBoldBlock 采用当前字体(作为块的第一个参数提供),添加粗体,并将其应用于当前块(作为块的第二个参数提供).

where addBoldBlock takes the current font (supplied as first argument to the block), adds bold, and applies it to the current chunk (supplied as second argument to the block).

这篇关于对 NSAttributedString 的一部分应用加粗,同时保留字体大小和字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆