How to change color of text strings inside UITextView in Swift3
<p>I have looked at some existing questions posts here and I tried to implement all code but ended up not being able to successfully implement any code. Actually, I think I comprehended how to change colors of some texts inside <code>UITextView</code> if a text is initially set, but what I do not understand is that when my <code>UITextView</code> began entering editing, it does not seem to be working properly at all. In the following, it is my attempted code that closely full fills my desired behaviour.</p>

<pre><code> func textViewDidBeginEditing(_ textView: UITextView) {

    let main_string = ""
    let getData: [String] = userDefaults.object(forKey: "myData") as! [String]
    print("\(getData)")

    let searchWords = "world"

        let range = (main_string as NSString).range(of: searchWords)

        let attribute = NSMutableAttributedString.init(string: main_string)
        attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range)

        mytextView.attributedText = attribute


}
</code></pre>

<p>I saved input data by naming <code>MyData</code>. I tried to use a for-loop to take all elements out of <code>getData</code> and use it as individual values. However, in the console, there are so many lines of explanation. I think this is a proper way to write, but my mac says nooooooo. However, If I set a <code>String</code> inside <code>main_string</code> and <code>searchWords</code>, for example, <em>"this is my question. I want people to help me from the world"</em> in main_string and <em>"world"</em> in searchWords as written in the code. Then after the app is being loaded, on my text view the word, "world" is highlighted in red perfectly, but after the world word, all text is in red. I do not understand why I am being tortured by this unknown bug.</p>

<p>So What I want to accomplish is </p>

<ol>
<li>from the saved date in my <code>myData</code>, I only want the stored words to be highlighted timely when users type in. For example, if a user types "hello" and "world". Then they are saved by <code>myData</code> and they are going to be highlighted only when typed. And switch back to the normal color when words which are not stored are typed. </li>
</ol>

<p>I assume I lack some explanation. If you need to know something, please point out for me. Thanks very much!!</p>