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

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

问题描述

我希望我的UILabel以以下方式显示文本6.022 * 10 23 . Swift对下标和上标有什么功能?

I want my UILabel to display text in following manner 6.022*1023. What functions 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. 将其分配给您的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天全站免登陆