Last active
June 2, 2021 21:31
-
-
Save aquajach/4d9398b95a748fd37e88 to your computer and use it in GitHub Desktop.
Swift: Highlight matched text in String between square brackets
This file contains 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
import UIKit | |
extension NSMutableAttributedString { | |
func highlightTarget(target: String, color: UIColor) -> NSMutableAttributedString { | |
let targetValue = String(target.characters.dropFirst().dropLast()) | |
let regPattern = "\\[\(targetValue)\\]" | |
if let regex = try? NSRegularExpression(pattern: regPattern, options: []) { | |
let matchesArray = regex.matchesInString(self.string, options: [], range: NSRange(location: 0, length: self.length)) | |
for match in matchesArray { | |
let attributedText = NSMutableAttributedString(string: targetValue) | |
attributedText.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: attributedText.length)) | |
self.replaceCharactersInRange(match.range, withAttributedString: attributedText) | |
} | |
} | |
return self | |
} | |
} | |
//Usage | |
let attributedString = NSMutableAttributedString(string: "Hello, [swift].[playground]") | |
if let textInArray = ["swift", "playground", "others"] { | |
for text in textInArray { | |
attributedString.highlightTarget(text, color: UIColor.blueColor()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//swift 5
extension NSMutableAttributedString {
}