Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexbaramilis/f6544aa0c0b29bd85fa01c6369890ff2 to your computer and use it in GitHub Desktop.
Save alexbaramilis/f6544aa0c0b29bd85fa01c6369890ff2 to your computer and use it in GitHub Desktop.
Swift UILabel Extension for setting attributedText with specified character indices in subscript.
import UIKit
extension UILabel {
/// Sets the attributedText property of UILabel with an attributed string
/// that displays the characters of the text at the given indices in subscript.
func setAttributedTextWithSubscripts(text: String, indicesOfSubscripts: [Int]) {
let font = self.font!
let subscriptFont = font.withSize(font.pointSize * 0.7)
let subscriptOffset = -font.pointSize * 0.3
let attributedString = NSMutableAttributedString(string: text,
attributes: [.font : font])
for index in indicesOfSubscripts {
let range = NSRange(location: index, length: 1)
attributedString.setAttributes([.font: subscriptFont,
.baselineOffset: subscriptOffset],
range: range)
}
self.attributedText = attributedString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment