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)"
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)"
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
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 -
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 UILabel
s 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.