1

I am creating a math app and would like to have a superscript 2. I have been unable to find a solution for xcode 8 that isn't a base line off set

finalFunc.text = "Converted: \(printA)(x+\(printB))^2+\(printC)" 

3 Answers3

2

Updated for Swift4

let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "xcode8", attributes: [NSAttributedString.Key.font:font!])
attString.setAttributes([NSAttributedString.Key.font:fontSuper!,NSAttributedString.Key.baselineOffset:10], range: NSRange(location:5,length:1))

labelname.attributedText = attString
Praveen
  • 1,791
  • 3
  • 20
  • 33
iainhunter
  • 487
  • 4
  • 10
1

Use this code -

let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "xcode8", attributes: [NSFontAttributeName:font!])
attString.setAttributes([NSFontAttributeName:fontSuper!,NSBaselineOffsetAttributeName:10], range: NSRange(location:5,length:1))
label1.attributedText = attString;

Output -

enter image description here

Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
0

For a simple to use Swift solution, you might want to checkout HandyUIKit. After importing it into your project (e.g. via Carthage – see instructions in README) you can do something like this:

import HandyUIKit

let someFont = UIFont.systemFont(ofSize: 20, weight: .medium)
"Converted: \(printA)(x+\(printB))^{2}+\(printC)".superscripted(font: someFont)

The last line will return an NSAttributedString which will look exactly like what you're looking for. Just assign it to a UILabels attributedText property and that's it!


If you're looking for subscripting a text, simply use subscripted(font:) instead. It will recognize structures like CO_{2}. There's also superAndSubscripted(font:) if you want to combine both.

See the docs for more information and additional examples.

Jeehut
  • 20,202
  • 8
  • 59
  • 80