How can make a UILabel look this way in Xcode12?
UILabel with superscript text
Add a Comment
How can make a UILabel look this way in Xcode12?
override func viewDidLoad() {
super.viewDidLoad()
let text = "1:47PM"
if let regularFont = UIFont(name: "Helvetica", size: 20.0), let subscriptFont = UIFont(name: "TamilSangamMN", size: 12.0) {
let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font: regularFont])
attString.setAttributes([.font: subscriptFont, .baselineOffset: 6], range: NSRange(location: text.count - 2, length: 2))
label.attributedText = attString
}
}
Several ways. Some examples:
//Using attributed string
let baseString = NSAttributedString(string: "1:47",
attributes: [
.font: UIFont.systemFont(ofSize: 48),
])
let pmString = NSAttributedString(string: "PM",
attributes: [
.baselineOffset: 16,
.font: UIFont.systemFont(ofSize: 28),
])
let attributedString = NSMutableAttributedString()
attributedString.append(baseString)
attributedString.append(pmString)
label1.attributedText = attributedString
label1.backgroundColor = .black
label1.textColor = .white
//Using Unicode characters
//let text = "1:47\u{1D3E}\u{1D39}"
let text = "1:47\u{1D2C}\u{1D39}"
label2.text = text
label2.backgroundColor = .black
label2.textColor = .white
If you can find a better font (which may not be included in standard iOS devices), the result may get better:
override func viewDidLoad() {
super.viewDidLoad()
let text = "1:47PM"
if let regularFont = UIFont(name: "Helvetica", size: 20.0), let subscriptFont = UIFont(name: "TamilSangamMN", size: 12.0) {
let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font: regularFont])
attString.setAttributes([.font: subscriptFont, .baselineOffset: 6], range: NSRange(location: text.count - 2, length: 2))
label.attributedText = attString
}
}