如何在Swift中使用下标和上标 [英] How to use subscript and superscript in Swift

查看:222
本文介绍了如何在Swift中使用下标和上标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的UILabel以下列方式显示文本:6.022 * 10 23 。快速对下标和上标有什么影响?

I want my UILabel to display text in following manner 6.022*1023. What fumctions does swift have for subscript and superscript?

推荐答案

大多数答案+例子都在ObjC中,但这是怎么做的在Swift中做。

Most of the answers+examples are in ObjC, but this is how to do it in Swift.

let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "6.022*1023", attributes: [.font:font!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:10], range: NSRange(location:8,length:2))
labelVarName.attributedText = attString

这给了我:

更详细的说明:


  1. 获取 UIFont 你想要的默认和上标样式,上标必须更小。

  2. 创建一个 NSMutableAttributedString 包含完整字符串和默认字体。

  3. 为要更改的字符添加属性( NSRange ),小/下标 UIFont NSBaselineOffsetAttributeName 值是你想要的金额垂直偏移它。

  4. Assi gn到你的 UILabel

  1. Get UIFont you want for both the default and superscript style, superscript must be smaller.
  2. Create a NSMutableAttributedString with the full string and default font.
  3. Add an attribute to the characters you want to change (NSRange), with the smaller/subscript UIFont, and the NSBaselineOffsetAttributeName value is the amount you want to offset it vertically.
  4. Assign it to your UILabel

希望这有助于其他Swift开发者因为我也需要这个。

这篇关于如何在Swift中使用下标和上标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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