I have looked at some exisiting 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 UITextView
if a text is initially set, but what I do not understand is that when my text tview began entering editing, it does not seem to be working properly at all. In the following, it is my attempted code that closely fulfills my desired behaviour;
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
}
I saved input data by naming is MyData
. I tried to use a for-loop to take all elements out of getData
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 String
inside main_string
and searchWords
, for example, "this is my question. I want people to help me from the world" in main_string and "world" in searchWords as written in the code. Then after the app is being loaded, on my text view the word, "world" is highlited 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.
So What I want to accomplish is
- from the saved date in my
myData
, 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 bymyData
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.
I assume I lack some explanation. If you need to know something, please point out for me. Thanks very much!!
In this I have taken string "world" as example. When you r typing in textview then This method is in working
But when You have already set initial text of textview then use this method
For Multiple Strings, You can do like this SWIFT 3
OBJECTIVE C
For Multiple Strings, You can do like this