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
Post a Comment