2017-03-25 13 views
1

私は話し言葉(例:幸せ、悲しみ、怒りなど)によって設定されたテキストフィールドの単語の色を変更しようとしています。 単語が2回以上話されている場合は機能しません。たとえば、私の弟が私を悲しませている、私は再び幸せです。それは最初の「幸せ」の色を変えるだけで、私はなぜそれほど正確ではないのですか?Swift 3.0スピーチからテキストへ:単語の色を変更する

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 

} 

ありがとう!

答えて

0

コードには2つの問題があります。

最初の問題は、例の句読点です。あなたがないとき:

text.components(separatedBy:" ") 

結果の配列は次のようになります。

["I'm", "feeling", "happy", ..., "making", "me", "sad."] 

悲しいが、それにピリオドを持っており、キーは単に「悲しい」であれば、あなたの感情の辞書には何が一致しません。あなたが二回あなたの例では、これが唯一の幸せの最初の出現の範囲を返します「幸せ」を持っているので、

let range:NSRange = (string.string as NSString).range(of: word) 

強調表示されますので、唯一の最初の幸せ:

第二の問題は、です。

感情辞書の各キーに正規表現を使用するのが最善の方法です。次に、の範囲をすべて取得するregex.matchesを呼び出すことができます。幸せまたは悲しいことが発生します。それをループして適切に色を設定することができます。

これがないと、あなたの例で動作するはずです以下:

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 
} 
+0

はこのためにどうもありがとうございます**素晴らしい**答え! – Mariella

関連する問題