Forked from sketchytech/Swift extension to NSMutableAttributedString (highlight and replace)
Last active
February 23, 2016 08:24
-
-
Save maxhis/8312d768cbb3eb2af656 to your computer and use it in GitHub Desktop.
Swift extension to NSMutableAttributedString adding methods for highlighting and replacing substrings (swift 2.0 supportted)
This file contains hidden or 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
extension NSMutableAttributedString { | |
func highlightStrings(stringToHighlight:String, usingRegex:Bool = false) { | |
var useRegex:NSRegularExpressionOptions? | |
if !usingRegex { | |
useRegex = NSRegularExpressionOptions.IgnoreMetacharacters | |
} | |
let exp = try! NSRegularExpression(pattern: stringToHighlight, options: useRegex!) | |
let arr = exp.matchesInString(self.string, options: [], range:NSRange(location: 0, length: self.length)) | |
for s in arr { | |
self.addAttribute(NSBackgroundColorAttributeName, value: UIColor.greenColor(), range: s.range) | |
} | |
} | |
func replaceStrings(find:String, replace:String, usingRegex:Bool = false) { | |
// var useRegex:NSRegularExpressionOptions? | |
// if !usingRegex { | |
// useRegex = NSRegularExpressionOptions.IgnoreMetacharacters | |
// } | |
// | |
// let exp = try! NSRegularExpression(pattern: find, options: useRegex!) | |
// let arr = exp.matchesInString(self.string, options: [], range:NSRange(location: 0, length: self.length)) | |
self.mutableString.replaceOccurrencesOfString(find, withString:replace, options:NSStringCompareOptions.RegularExpressionSearch, range:NSRange(location: 0, length: self.length)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment