How do I use subscript and superscript in Swift?
Most of the answers+examples are in ObjC, but this is how to do it in 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
This gives me:
In a more detailed explanation:
- Get
UIFont
you want for both the default and superscript style, superscript must be smaller. - Create a
NSMutableAttributedString
with the full string and default font. - Add an attribute to the characters you want to change (
NSRange
), with the smaller/subscriptUIFont
, and theNSBaselineOffsetAttributeName
value is the amount you want to offset it vertically. - Assign it to your
UILabel
Hopefully this helps other Swift devs as I needed this as well.
How to type subscripts/superscripts in Xcode string literals?
With these string literals, it's not a question of character position or font size. These are special unicode superscript/subscript characters. If you go to the macOS keyboard preferences and choose "Show keyboard and emoji viewers in menu bar", you'll have a new option in your menu bar "Show emoji & symbols". You can then, for example, type "2" in the searchbox and you'll then see subscript and superscript rendition in the "related characters" section:
So, this is not a general subscript/subscripting feature, but dedicated unicode characters for just a few common subscripts/superscripts (e.g. "2", "x", etc.).
Note, if you need more fine grained control over fonts, baseline adjustments, etc., many user interface controls support the use of attributed strings, e.g.:
let bigFont = UIFont.systemFont(ofSize: 20)
let smallFont = UIFont.systemFont(ofSize: 12)
let title = NSMutableAttributedString(string: "foo", attributes: [.font: bigFont])
title.append(NSMutableAttributedString(string: "bar", attributes: [.font: smallFont, .baselineOffset: 10]))
button.setAttributedTitle(title, for: .normal)
Yielding:
Or, as described in this answer, you can apparently also do:
let string = "foobar"
let range = NSRange(location: 3, length: 3)
let title = NSMutableAttributedString(string: string)
let superscript = NSAttributedStringKey(rawValue: kCTSuperscriptAttributeName as String)
title.addAttributes([superscript: 1], range: range) // Use 1 for superscript; use -1 for subscript
But your code snippet is clearly just using the predefined unicode superscript/subscript characters. These various programmatic approaches can be useful, though, if you need to render something that doesn't already exist in unicode.
Superscript string in Swift
There are Two Ways:
Way 1:- NSAttributed String
let mainText = "Here is a example of attributedString"
let attributeText = "attributedString"
let range = (mainText as NSString).range(of: attributeText)
let attributedString = NSMutableAttributedString(string:mainText)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
attribute.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14) , range: range)
lblTitle.attributedText = attributedString
Way :- 2 You can use HTML Property:
let htmlString = "This is some text!"
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
SwiftUI Text - How to convert 10^12 to 10 the correct format
This kind of things are much easier in SwiftUI, there is lots of ways for this job in SwiftUI one of them could be this down code:
struct ContentView: View {
@State var yourFirstText: String = "The universe has "
@State var yourLastText: String = " bla bla bla"
var body: some View {
Text(yourFirstText) + Text("10") + Text("12").font(Font.footnote).baselineOffset(6.0) + Text(yourLastText)
}
}
Is there a SwiftUI way of making text superscript or subscript?
Here's a generic way using .baselineOffset
:
Text("Company")
.font(.callout)
+ Text("TM")
.font(.system(size: 8.0))
.baselineOffset(6.0)
I'm sure there's a way to get the correct offset dynamically using CTFont
, but I think it may be a pain. A sloppy way would be to wrap the Text View(s)? in a GeometryReader, and use the height to try and position it so it looks good.
You can also use Unicode for some symbols (like ™):
Text("Company\u{2122}")
How to add superscript when a button is pressed?
let font:UIFont? = UIFont.systemFont(ofSize: 20.0)
let fontSuper:UIFont? = UIFont.systemFont(ofSize: 10.0)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "YourLabel", attributes: [.font:font!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:10], range: NSRange(location:4,length:5))
yourLabel.attributedText = attString
Related Topics
How to Add Minutes to Current Time in Swift
Generate a Random Float Between 0 and 1
How to Log a Method's Execution Time Exactly in Milliseconds
Custom Installed Font Not Displayed Correctly in Uilabel
iOS 8 Rotation Methods Deprecation - Backwards Compatibility
Xcode 4.5 and iOS 4.2.1 Incompatibility
How to Create a Scroll View with a Page Control Using Swift
Check If a Uiscrollview Reached the Top or Bottom
iOS App Error - Can't Add Self as Subview
Static Table View Outside Uitableviewcontroller
iOS Memory Allocation - How Much Memory Can Be Used in an Application
How to Make an Uipickerview Component Wrap Around
Swift Programmatically Navigate to Another View Controller/Scene
How to Fix Xcode "Dtassetproviderservice Could Not Start.." Error