如何在Swift中使用下标和上标

Ada*_*ung 37 ios swift

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

For*_*ter 78

大多数答案+示例都在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
Run Code Online (Sandbox Code Playgroud)

这给了我:

SuperScript示例

在更详细的解释中:

  1. 获取UIFont你想要的缺省值和标风格,标必须更小.
  2. NSMutableAttributedString使用完整字符串和默认字体创建一个.
  3. NSRange使用较小的/下标向要更改的字符添加属性(),值是要垂直偏移UIFontNSBaselineOffsetAttributeName值.
  4. 将它分配给你的 UILabel

希望这也有助于其他Swift开发者,因为我也需要它.


Chr*_*ris 12

作为一种不同的方法,我编写了一个函数,它接受一个字符串,其中指数被添加到^诸如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
}
Run Code Online (Sandbox Code Playgroud)

这是一种蛮力方法,但是如果您不想处理属性字符串或者希望字符串独立于字体,它就可以工作.


Gle*_*wes 10

如果你可以使用看起来不完美的文本,并且只需要一个字符子集就可以使用unicode上标和下标数字:⁰¹³⁴⁵⁶⁷⁸⁹₂₂₂₃₄₄₅₅₅₅₅₅₅₅⁹⁹⁹₂ ₇₇₈这样做的好处是不那么累赘.


Atk*_*tka 10

我写了以下扩展名,或者你可以将它作为一个函数使用,它对我来说效果很好.您可以通过跳过对您来说不重要的部分来修改它

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 i.e. +/- 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}
  }
Run Code Online (Sandbox Code Playgroud)

例子:

let attStr1 = NSMutableAttributedString().characterSubscriptAndSuperscript(
               string: "23 x 456", 
               characters:["3","5"], 
               type: .aSuper, 
               fontSize: 20, 
               scriptFontSize: 15, 
               offSet: 10, 
               length: [1,2], 
               alignment: .left)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

let attStr2 = NSMutableAttributedString().characterSubscriptAndSuperscript(
           string: "H2SO4", 
           characters: ["2","4"], 
           type: .aSub, 
           fontSize: 20, 
           scriptFontSize: 15, 
            offSet: 8, 
           length: [1,1], 
           alignment: .left)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


ras*_*slv 5

我的解决方案是 String 的扩展

extension String {
    func setAsSuperscript(_ textToSuperscript: String) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: self)
        let foundRange = attributedString.mutableString.range(of: textToSuperscript)

        let font = UIFont.systemFont(ofSize: 13)

        if foundRange.location != NSNotFound {
            attributedString.addAttribute(.font, value: font, range: foundRange)
            attributedString.addAttribute(.baselineOffset, value: 0.5, range: foundRange)
        }

        return attributedString
    }
}
Run Code Online (Sandbox Code Playgroud)

及用法:

let placeholder = "Required value*".setAsSuperscript("*")
myLabel.attributedText = placeholder
Run Code Online (Sandbox Code Playgroud)