Search code examples
swifttextuilabelnsattributedstringnsmutableattributedstring

how to set the position for part of the text in UILabel


i need to create some NSMutableAttributedString with setting for the text position in UILabel how can i do this in Swift? The result should be like this (x+y)³ but instead ³ some text I write the some code

    let stringTest = "(x+y)123"
    let myRange = NSRange(location: 5, length: 3)
    let myAttributeMainText = [ NSFontAttributeName: UIFont(name: "Arial", size: 18.0)! ]
    let myAttributeDegreeText = [ NSFontAttributeName: UIFont(name: "Arial", size: 10.0)! ]
    let myString = NSMutableAttributedString(string: stringTest, attributes: myAttributeMainText )
    myString.addAttributes(myAttributeDegreeText, range: myRange)
    testLabel.attributedText = myString

please help me find a way to raise the last 3 digits in the top of UILabel


Solution

  • You need to use an NSBaselineOffsetAttributeName for making the numbers appear as exponents, for example:

    let myAttributeDegreeText = [NSBaselineOffsetAttributeName: 6, NSFontAttributeName: UIFont(name: "Arial", size: 10.0)!]
    

    enter image description here