Change the style of an array of String inside a TextView - swift - EDIT -


my first question how change font of word example "test" in textview, , answered correctly @bkrl , @torongo.

func changealloccurence(of string: string, font: uifont) -> nsattributedstring {     let attributedstring = nsmutableattributedstring(string: self)     var range = nsmakerange(0, attributedstring.mutablestring.length)      while(range.location != nsnotfound)     {         range = attributedstring.mutablestring.range(of: string, options: .caseinsensitive, range: range)         if(range.location != nsnotfound)         {             attributedstring.addattribute(nsfontattributename,                                           value: font,                                           range: range)             range = nsmakerange(range.location + range.length, self.characters.count - (range.location + range.length));         }     }      return attributedstring } 

as still not familiar above code, tried add few lines in order generalize code can works array of strings , not 1 string. sure didn't works cause changed font of last word reasonable cause final changes last word "usage":

        let words = ["example", "usage"]         word in words {         let attributedtext = text.changealloccurence(of: word, font: uifont.boldsystemfont(ofsize: 17))         textview.attributedtext = attributedtext     } 

can advise how improve code provided @toromgo in order work array of strings instead of one?

as have changed question, ihave updated answer accordingly. please try this:

extension string {      func changealloccurence(of strings: [string], font: uifont) -> nsattributedstring {         let attributedstring = nsmutableattributedstring(string: self)         eachstring in strings {             var range = nsmakerange(0, attributedstring.mutablestring.length)              while(range.location != nsnotfound)             {                 range = attributedstring.mutablestring.range(of: eachstring, options: .caseinsensitive, range: range)                 if(range.location != nsnotfound)                 {                     attributedstring.addattribute(nsfontattributename,                                                   value: font,                                                   range: range)                     range = nsmakerange(range.location + range.length, self.characters.count - (range.location + range.length));                 }             }         }         return attributedstring     }  } 

i have run code , working.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -