iOS 上 NSAttributedString 中类似 NSBackgroundColorAttributeName 的属性?
我计划使用 NSAttributedString 来突出显示与用户搜索的匹配查询的字符串部分。但是,我找不到与 NSBackgroundColorAttributeName
等效的 iOS 版本 - 没有 kCTBackgroundColorAttributeName
。是否存在这样的事情,类似于 NSForegroundColorAttributeName
变成 kCTForegroundColorAttributeName
?
I was planning on using NSAttributedString to highlight portions of strings with the matching query of a user's search. However, I can't find an iOS equivalent of NSBackgroundColorAttributeName
—there's no kCTBackgroundColorAttributeName
. Does such a thing exist, similar to the way NSForegroundColorAttributeName
becomes kCTForegroundColorAttributeName
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,核心文本中不存在这样的属性,您必须在文本下方绘制自己的矩形来模拟它。
基本上,您必须找出要填充字符串中给定范围的矩形。如果您使用生成
CTFrame
的CTFramesetter
进行布局,则需要使用CTFrameGetLines
和CTFrameGetLineOrigins 获取其线条及其原点
。然后迭代这些行并使用
CTLineGetStringRange
找出哪些行属于您要突出显示的范围。要填充矩形,请使用CTLineGetTypgraphicBounds
(对于高度)和CTLineGetOffsetForStringIndex
(对于水平偏移和宽度)。No, such an attribute doesn't exist in Core Text, you'll have to draw your own rectangles underneath the text to simulate it.
Basically, you'll have to figure out which rectangle(s) to fill for a given range in the string. If you do your layout with a
CTFramesetter
that produces aCTFrame
, you need to get its lines and their origins usingCTFrameGetLines
andCTFrameGetLineOrigins
.Then iterate over the lines and use
CTLineGetStringRange
to find out which lines are part of the range you want to highlight. To get the rectangles to fill, useCTLineGetTypographicBounds
(for the height) andCTLineGetOffsetForStringIndex
(for the horizontal offset and width).NSBackgroundColorAttributeName 在 iOS 6 中可用,您可以通过以下方式使用它:
drawInRect:
将支持 NSBackgroundColorAttributeName 以及 iOS 6 支持的所有 NS*AttributeName。对于 CTFrameDraw() 不支持背景文本颜色。
代码:
NSBackgroundColorAttributeName is available in iOS 6, and you can use it by following way:
drawInRect:
will support NSBackgroundColorAttributeName and all NS*AttributeNames supported by iOS 6.For CTFrameDraw() there is no support for background text color.
Code: