如何使用 NSAttributedString 制作下标和上标?
我需要为化学公式(H2O、Na^2+ 等)制作下标吗?
这是否可以与 NSAttributedString 相关,或者是否有其他/更简单的方法来制作下标?
I need to make subscripts for chemistry formulas (H2O, Na^2+, etc)?
Is this possible to do with NSAttributedString, or is there an alternative/easier way to make subscripts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是我在 iOS 6 中所做的。首先添加 CoreText 和 QuartzCore 框架。然后导入:
我做了一个小函数,输入一个普通的 NSString 并导出一个 NSMutableAttributedString,最后一个字符在上标中。可以修改它以允许设置上标或下标,将 kCTSuperscriptAttributeName 值更改为 -1。您还可以添加一个变量来指定将上标放在字符串中的位置。现在它只是假设字符串的结尾。
现在,当我想使用它时,我可以执行以下操作将其放入 UITextField 中:
我希望这对其他人有帮助,那里的示例并不多!
Here's what I did in iOS 6. First add the CoreText, and QuartzCore frameworks. Then import:
I made a small function that inputs a plain NSString and exports a NSMutableAttributedString with the last character in superscript. This can be modified to allow setting superscript or subscript, change kCTSuperscriptAttributeName value to -1. Also you could add a variable to specify where to put the superscript in the string. Right now it just assumes the end of the string.
Now when I want to use it I can do the following to put it in a UITextField:
I hope this helps somebody else, there's not many examples out there!
这可以通过
NSAttributedString
来完成。您要查找的属性常量取决于您的平台。对于 Mac OS X,它是NSSuperscriptAttributeName
,在 iOS 上它是kCTSuperscriptAttributeName
。为下标传入负值。唯一需要注意的是,iOS 上的
UILabel
无法绘制NSAttributedString
(不过,请为 iOS 6 祈祷)。您需要使用 Core Text 绘制文本,或者找到可以绘制NSAttributedString
的UILabel
的第三方替代品。This is possible to do with
NSAttributedString
. The attribute constant you're looking for depends on your platform. For Mac OS X it isNSSuperscriptAttributeName
and on iOS it iskCTSuperscriptAttributeName
. Pass in a negative value for subscript.The only caveat is that
UILabel
on iOS can't drawNSAttributedString
s (yet, fingers crossed for iOS 6). You would need to draw the text using Core Text or find some third party replacement forUILabel
that can draw anNSAttributedString
.在 iOS 上,我错过了 kCTSuperscriptAttributeName 常量,但在字体大小和“基线”方面获得了良好的结果。对于不太听话的字体,它也为您提供了更多的控制权:
On iOS, I had missed the kCTSuperscriptAttributeName constant but had good results with font size and "baseline". It gives you a little more control too for less obedient fonts:
如果你想让它更干净一点,你也可以执行以下操作
you can also do the following if you want to make it a litle cleaner