问题
I'm trying to change the color of words in textfield set by spoken words (ex: happy, sad, angry, etc). It doesn't work if the word is spoken more than once. For example, if I say, "I'm feeling happy because my cat is being nice to me. My brother is making me sad. I'm happy again." it will only change the color of the first 'happy' and I'm not exactly sure why.
func setTextColor(text: String) -> NSMutableAttributedString {
let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
let words:[String] = text.components(separatedBy:" ")
for word in words {
if emotionDictionary.keys.contains(word) {
let range:NSRange = (string.string as NSString).range(of: word)
string.addAttribute(NSForegroundColorAttributeName, value: emotionDictionary[word], range: range)
}
}
return string
}
Thanks!
回答1:
There are two problems with your code.
The first problem is the punctuation in your example. When you do:
text.components(separatedBy:" ")
The resulting array will look like:
["I'm", "feeling", "happy", ..., "making", "me", "sad."]
The sad has a period in it and won't match what's in your emotion dictionary if the key is just "sad".
The second problem is with:
let range:NSRange = (string.string as NSString).range(of: word)
Since you have "happy" twice in your example this will only return the range of the first occurrence of happy, so only the first happy will be highlighted.
The best path is to use a regular expression for each key in your emotion dictionary. Then you can call regex.matches which will get you the ranges of all occurrences of happy or sad. You can then loop over that and set the color appropriately.
This does the following and should work with your example:
func setTextColor(text: String) -> NSMutableAttributedString {
let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
for key in emotionDictionary.keys {
do {
let regex = try NSRegularExpression(pattern: key)
let allMatches = regex.matches(in: text, options: [], range: NSMakeRange(0, string.length))
.map { $0.range }
for range in allMatches {
string.addAttribute(NSForegroundColorAttributeName, value: emotionDictionary[key], range: range)
}
}
catch { }
}
return string
}
来源:https://stackoverflow.com/questions/43020608/swift-3-0-speech-to-text-changing-color-of-words