如何在Swift中使用下标和上标
我想我的UILabel以下面的方式显示文本6.022 * 10 23 。 下标和上标有什么特点?
大多数答案+例子都在ObjC中,但是这是如何在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
这给了我:
在更详细的解释中:
- 获取
UIFont
你想要的默认和上标风格,上标必须更小。 - 用完整的string和默认字体创build一个
NSMutableAttributedString
。 - 使用较小的/下标
UIFont
将属性添加到要更改的字符(NSRange
),NSBaselineOffsetAttributeName
值是要垂直偏移它的数量。 - 分配给你的
UILabel
希望这有助于其他Swift开发人员,因为我也需要这个。
作为一个不同的方法,我写了一个函数,它接受一个string,其中指数前缀为^
2^2•3•5^2
并返回2²•3•5²
func exponentize(str: String) -> String { let supers = [ "1": "\u{00B9}", "2": "\u{00B2}", "3": "\u{00B3}", "4": "\u{2074}", "5": "\u{2075}", "6": "\u{2076}", "7": "\u{2077}", "8": "\u{2078}", "9": "\u{2079}"] var newStr = "" var isExp = false for (_, char) in str.characters.enumerate() { if char == "^" { isExp = true } else { if isExp { let key = String(char) if supers.keys.contains(key) { newStr.append(Character(supers[key]!)) } else { isExp = false newStr.append(char) } } else { newStr.append(char) } } } return newStr }
这是一种暴力方法,但是如果你不想处理属性string,或者你希望你的string独立于字体,它就可以工作。
如果你能够看到看起来不太完美的文本,只需要一个字符的子集,你就可以使用unicode的上标和下标数字:1 2 3 4 5 6 6 ₉₈₉这样做的好处是less了很多麻烦。
我写了下面的扩展名,或者你可以用它作为一个函数,它对我来说工作的很好。 您可以通过跳过对您不重要的部分来修改它
extension NSMutableAttributedString { enum scripting : Int { case aSub = -1 case aSuper = 1 } func characterSubscriptAndSuperscript(string:String, characters:[Character], type:scripting, fontSize:CGFloat, scriptFontSize:CGFloat, offSet:Int, length:[Int], alignment:NSTextAlignment)-> NSMutableAttributedString { let paraghraphStyle = NSMutableParagraphStyle() // Set The Paragraph aligmnet , you can ignore this part and delet off the function paraghraphStyle.alignment = alignment var scriptedCharaterLocation = Int() //Define the fonts you want to use and sizes let stringFont = UIFont.boldSystemFont(ofSize: fontSize) let scriptFont = UIFont.boldSystemFont(ofSize: scriptFontSize) // Define Attributes of the text body , this part can be removed of the function let attString = NSMutableAttributedString(string:string, attributes: [NSFontAttributeName:stringFont,NSForegroundColorAttributeName:UIColor.black,NSParagraphStyleAttributeName: paraghraphStyle]) // the enum is used here declaring the required offset let baseLineOffset = offSet * type.rawValue // enumerated the main text characters using a for loop for (i,c) in string.characters.enumerated() { // enumerated the array of first characters to subscript for (theLength,aCharacter) in characters.enumerated() { if c == aCharacter { // Get to location of the first character scriptedCharaterLocation = i //Now set attributes starting from the character above attString.setAttributes([NSFontAttributeName:scriptFont, // baseline off set from . the enum ie +/- 1 NSBaselineOffsetAttributeName:baseLineOffset, NSForegroundColorAttributeName:UIColor.black], // the range from above location range:NSRange(location:scriptedCharaterLocation, // you define the length in the length array // if subscripting at different location // you need to define the length for each one length:length[theLength])) } } } return attString} }
例子:
let attStr1 = NSMutableAttributedString().characterSubscriptAndSuperscript( string: "23 x 456", characters:["3","5"], type: .aSuper, fontSize: 20, scriptFontSize: 15, offSet: 10, length: [1,2], alignment: .left)
let attStr2 = NSMutableAttributedString().characterSubscriptAndSuperscript( string: "H2SO4", characters: ["2","4"], type: .aSub, fontSize: 20, scriptFontSize: 15, offSet: 8, length: [1,1], alignment: .left)
对于简单易用的Swift解决scheme ,您可能需要签出HandyUIKit 。 导入到您的项目(例如通过迦太基 – 见自述文件中的说明)后,你可以做这样的事情:
import HandyUIKit "6.022*10^{23}".superscripted(font: UIFont.systemFont(ofSize: 20, weight: .medium))
这一行将返回一个NSAttributedString
,它看起来就像你正在寻找的东西 。 只需将其分配给UILabel
的attributedText
UILabel
attributedText
,就是这样!
如果你正在寻找一个文本的下标 ,只需使用subscripted(font:)
来代替。 它将识别CO_{2}
等结构。 还有superAndSubscripted(font:)
如果你想要结合两者 。
有关更多信息和其他示例,请参阅文档 。