Last active
April 16, 2019 15:55
-
-
Save alexbaramilis/f6544aa0c0b29bd85fa01c6369890ff2 to your computer and use it in GitHub Desktop.
Swift UILabel Extension for setting attributedText with specified character indices in subscript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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