Last active
          February 23, 2016 07:58 
        
      - 
      
- 
        Save sketchytech/7cd6ab241a22fc2a3ffc to your computer and use it in GitHub Desktop. 
    Swift extension to NSMutableAttributedString adding methods for highlighting and replacing substrings
  
        
  
    
      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 = NSRegularExpression(pattern: stringToHighlight, options: useRegex ?? nil, error: nil) | |
| let arr = exp.matchesInString(self.string, options: nil, 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 = NSRegularExpression(pattern: find, options: useRegex ?? nil, error: nil) | |
| let arr = exp.matchesInString(self.string, options: nil, 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
  
            
Not working with swift 2.0?