UILabel is (notoriously) incompatible with HTML, and doesn’t automatically superscript ™ and ®. So, here’s a method, in Swift 2 (which until only recently didn’t like string lengths very much). Input the base font, the superscripted font (this should be smaller, but doesn’t have to be), and the string in question to get an NSMutableAttributedString object back. To subscript, set the value of kCTSuperscriptAttributeName to -1.

// scans for ® and ™ and superscripts them

@objc func superscriptTheTMandR(string:NSString, baseFont:UIFont, superscriptFont:UIFont) ->(NSMutableAttributedString) {

let string = (string as String)+" " // makes sure we include any trailing ® or ™

// find occurances of ®

var arrayR = string.characters.split {$0 == "®"}.map(String.init)

// arrayR is only for length, so make each array element the string's cumulative lengths

if arrayR.count > 1 {

for (var i = 1; i < arrayR.count; i++) {

arrayR[i] = arrayR[i-1] + " " + arrayR[i]

}

}

// find occurances of ™ var arrayTM = string.characters.split {$0 == "™"}.map(String.init)

// arrayTM is only for length, so make each array element the string's cumulative lengths

if arrayTM.count > 1 {

for (var i = 1; i < arrayTM.count; i++) {

arrayTM[i] = arrayTM[i-1] + " " + arrayTM[i]
}
}

let aString = NSMutableAttributedString(string: string as String)

aString.beginEditing()

aString.addAttribute(NSFontAttributeName, value: baseFont, range: NSRange(location:0, length:aString.length))

for (var i = 0; i < arrayR.count - 1; i++) {

let stringer = arrayR[i]

aString.addAttribute(kCTSuperscriptAttributeName as String, value: 1, range: NSRange(location:NSString(string:stringer).length, length:1))

aString.addAttribute(NSFontAttributeName, value: superscriptFont, range: NSRange(location:NSString(string:stringer).length, length:1))
}

for (var i = 0; i < arrayTM.count - 1; i++) {

let stringer = arrayTM[i]

aString.addAttribute(kCTSuperscriptAttributeName as String, value: 1, range: NSRange(location:NSString(string:stringer).length, length:1))

aString.addAttribute(NSFontAttributeName, value: superscriptFont, range: NSRange(location:NSString(string:stringer).length, length:1))
}

aString.endEditing()

return aString
}

This post has already been read 0 times!

Edit