Skip to content

Instantly share code, notes, and snippets.

@ttepasse
Created November 19, 2014 12:32
Show Gist options
  • Save ttepasse/730c5e66dd39022ca3a3 to your computer and use it in GitHub Desktop.
Save ttepasse/730c5e66dd39022ca3a3 to your computer and use it in GitHub Desktop.
import UIKit
extension String {
func NSRangeOfString(string: String) -> NSRange? {
if let range = self.rangeOfString(string) {
let loc = distance(self.startIndex, range.startIndex)
let length = distance(range.startIndex, range.endIndex)
return NSMakeRange(loc, length)
} else {
return nil
}
}
}
let hello = "Hëllø Wœrld!"
let cjk = "Christian"
// Using an ASCII string. The metrics compared to the unicodian multi-byte string
// should be the same, because of the same amount of graphemes.
let formattedHello = NSMutableAttributedString(string: "Hello World and others!")
if let range = hello.NSRangeOfString("Wœrld") {
formattedHello.addAttribute(NSForegroundColorAttributeName,
value: UIColor.redColor(),
range: range)
formattedHello.replaceCharactersInRange(range, withString: cjk)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment