Last active
June 20, 2019 21:39
-
-
Save codingmanu/9c95df6e7b98132bf7ed757672e88c01 to your computer and use it in GitHub Desktop.
SwiftUI Text coloring word initializer
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
// SwiftUI Text Initializer replacing occurences of a given word with a colored version. | |
// Made by Manuel Gomez (@codingManu) on 2019/06/19 | |
extension Text { | |
public init<S>(_ content: S, making: S, _ color: Color) where S : StringProtocol { | |
let comps = content.components(separatedBy: making) | |
var baseText = Text("") | |
if comps[0] != making { | |
baseText = Text(comps[0]) | |
} | |
for component in comps[1...] { | |
baseText = baseText + (Text(making).color(color)) | |
baseText = baseText + (Text(component)) | |
} | |
self = baseText | |
} | |
} | |
// Tokenizer extension copied from some comment on StackOverflow. Can't find the source now. | |
extension String { | |
func tokenize() -> [String] { | |
let inputRange = CFRangeMake(0, self.count) | |
let flag = UInt(kCFStringTokenizerUnitWord) | |
let locale = CFLocaleCopyCurrent() | |
let tokenizer = CFStringTokenizerCreate( kCFAllocatorDefault, self as CFString, inputRange, flag, locale) | |
var tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer) | |
var tokens : [String] = [] | |
while tokenType != [] | |
{ | |
let currentTokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer) | |
let substring = self.substringWithRange(aRange: currentTokenRange) | |
tokens.append(substring) | |
tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer) | |
} | |
return tokens | |
} | |
func substringWithRange(aRange : CFRange) -> String { | |
let nsrange = NSMakeRange(aRange.location, aRange.length) | |
let substring = (self as NSString).substring(with: nsrange) | |
return substring | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: