Skip to content

Instantly share code, notes, and snippets.

@ttepasse
Last active August 29, 2015 14:13
Show Gist options
  • Save ttepasse/1ff2cb30102d4fae09f7 to your computer and use it in GitHub Desktop.
Save ttepasse/1ff2cb30102d4fae09f7 to your computer and use it in GitHub Desktop.
import UIKit
class FormattableAttributedString {
/* class */ let formatPattern = NSRegularExpression(pattern: "\\{(\\w+)\\}", options: nil, error: nil)!
var formatString : NSMutableAttributedString
var formatSpecifiers : [String: NSRange] = [:]
init(_ string: String) {
self.formatString = NSMutableAttributedString(string: string)
let str = string as NSString
let range = NSMakeRange(0, str.length)
self.formatPattern.enumerateMatchesInString(str, options: nil, range: range, usingBlock: {
(result, flags, stop) -> Void in
let specifier = str.substringWithRange( result.rangeAtIndex( 1 ) )
self.formatSpecifiers[specifier] = result.range
})
}
func setAttributes(attributes: [NSObject: AnyObject], forSpecifier: String) {
if let range = self.formatSpecifiers[forSpecifier] {
self.formatString.setAttributes(attributes, range: range)
}
}
func format (mapping: [String:String]) -> NSMutableAttributedString? {
if mapping.isEmpty {
return nil
}
var nongivenSpecifier = false
for specifier in self.formatSpecifiers.keys {
if let target = mapping[specifier] {
continue
} else {
nongivenSpecifier = true
break
}
}
if nongivenSpecifier {
return nil
}
var result = NSMutableAttributedString(attributedString: self.formatString)
for (specifier, range) in self.formatSpecifiers {
result.replaceCharactersInRange(range, withString: mapping[specifier]!)
}
return result
}
}
let redColorAttribute = [NSForegroundColorAttributeName : UIColor.redColor()]
let string = FormattableAttributedString("Add {tagname} tag")
string.setAttributes(redColorAttribute, forSpecifier: "tagname")
string.format(["tagname" : "FooBar"])!
string.format(["tagname" : "Jeena"])!
let complexString = FormattableAttributedString("Die {star} scheint mir aus dem {bodypart}, du {adressed}")
for tag in ["star", "bodypart", "adressed"] {
complexString.setAttributes(redColorAttribute, forSpecifier: tag)
}
complexString.format([
"star" : "Sonne",
"bodypart" : "Arsche",
"adressed" : "Depp",
"unused" : "unused"
])!
if let x = string.format(["eins" : "zwei"]) {
println("huch?")
} else {
println("falscher Tag")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment