How to Change Color of Single Word in Uitextview and Uitextfield

Is it possible to change color of single word in UITextView and UITextField

Yes you need to use NSAttributedString for that, find the RunningAppHere.

Scan through the word and find the range of your word and change its color.

EDIT:

- (IBAction)colorWord:(id)sender {
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.text.text];

NSArray *words=[self.text.text componentsSeparatedByString:@" "];

for (NSString *word in words) {
if ([word hasPrefix:@"@"]) {
NSRange range=[self.text.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
}
[self.text setAttributedText:string];
}

EDIT 2 : see the screenshot
Sample Image

UITextView change text color of specific text

Sorry, I just noticed your message. Here is a working example (tested in a playground):

import UIKit


func apply (string: NSMutableAttributedString, word: String) -> NSMutableAttributedString {
let range = (string.string as NSString).rangeOfString(word)
return apply(string, word: word, range: range, last: range)
}

func apply (string: NSMutableAttributedString, word: String, range: NSRange, last: NSRange) -> NSMutableAttributedString {
if range.location != NSNotFound {
string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
let start = last.location + last.length
let end = string.string.characters.count - start
let stringRange = NSRange(location: start, length: end)
let newRange = (string.string as NSString).rangeOfString(word, options: [], range: stringRange)
apply(string, word: word, range: newRange, last: range)
}
return string
}

var chordsArray = ["Cmaj", "Bbmaj7"]
var text = "Cmaj Bbmaj7 I Love Swift Cmaj Bbmaj7 Swift"
var newText = NSMutableAttributedString(string: text)

for word in chordsArray {
newText = apply(newText, word: word)
}

newText

Programatically change some words' color in an UITextView

You are not getting the range correctly, here is an example of using attributed strings in Swift 3.0:

// get initial text as a String type (you will get this from your textview)
let initialText = "Swift Attributed String"

// create an attribute for the text color, I chose blue color
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]

// create the attributed string and add the blue color attribute
let myString = NSMutableAttributedString(string: initialText, attributes: myAttribute )

// range starting at location 6 with a lenth of 10: "Attributed"
var myRange = NSRange(location: 6, length: 10)

// OR get range of specific string in initialText
let newRange = (initialText as NSString).range(of: "Attributed")

// change the range of the word "Attributed" to have red text color
myString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: newRange)

// create another attribute for highlighting
let anotherAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]
// set the range of the "Attributed" part of the string to a yellow highlight
myString.addAttributes(anotherAttribute, range: newRange)

You can use this strategy to do whatever formatting you need to do with your string. Just make sure that the range that you are getting is correct.

Change a specific words color in a UITextView

Try this code

import UIKit

extension String {
func getRanges(of string: String) -> [NSRange] {
var ranges:[NSRange] = []
if contains(string) {
let words = self.components(separatedBy: " ")
var position:Int = 0
for word in words {
if word.lowercased() == string.lowercased() {
let startIndex = position
let endIndex = word.count
let range = NSMakeRange(startIndex, endIndex)
ranges.append(range)
}
position += (word.count + 1)
}
}
return ranges
}
func setColorToChar(_ chars: [String] , color: [UIColor]) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self)

if chars.count != color.count {
fatalError("Colors are not added correctly")
}

// let ranges = getRanges(of: char)
for i in 0.. let ranges = getRanges(of: chars[i])
for range in ranges {
attributedString.addAttributes([NSForegroundColorAttributeName: color[i]], range: range)
}
}

return attributedString
}
}

class ViewController: UIViewController,UITextViewDelegate {

@IBOutlet weak var myTextView: UITextView!

override func viewDidLoad() {
super.viewDidLoad()
myTextView.delegate = self

}

func textViewDidChange(_ textView: UITextView) {

textView.attributedText = textView.text.setColorToChar(["//","let"], color: [.red,.green])
}


}

Result screenshot

Sample Image

Keeping track of and changing color of text in UITextView

For the first issue, it's because you should do an "else" case, and reset the color and the boolean value.
You should add:

} else {
didFindACertainWord = false
textView.attributedText = attributedString
}

For the second one, you shouldn't need to keep working only on the last word, instead check if there is a match in the whole string.

Not tested, but it should to the work:

func textViewDidChange(_ textView: UITextView) {

let attributedString = NSMutableAttributedString(string: textView.text,
attributes: [.font: UIFont(name: "Avenir-Roman", size: 18)])

let allWords = attributedString.string.components(separatedBy: CharacterSet.whitespaces)
if let firstMatch = allWords.first(where: { return certainWords.contains($0)}) {
didFindACertainWord = true
let firstMatchRange = (attributedString.string as NSString).range(of: firstMatch)
attributedString.addAttribute(.foregroundColor, value: UIColor.blue, range: firstMatchRange)
} else {
didFindACertainWord = false
}
textView.attributedText = attributedString
}

How to change color of text strings inside UITextView in Swift3

In this I have taken string "world" as example. When you r typing in textview then This method is in working

func textViewDidChange(_ textView: UITextView) {
let attrStr = NSMutableAttributedString(string:txtview.text)
let inputLength = attrStr.string.characters.count
let searchString = "world"
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
if (range.location != NSNotFound) {
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
textView.attributedText = attrStr
}
}
}

But when You have already set initial text of textview then use this method

func textViewDidBeginEditing(_ textView: UITextView) {
//Just set your text as you set in textview
let attrStr = NSMutableAttributedString(string: "hello world I ma jeckjklwefljlwjflkjwfkljelwfjklfgjwklfjlkwgjwlgkjwklsgjklsjgklsdjgkljdslkgjsdlkgjlksdjgldjsgldjskl world nsfhjklshfklhsllsd fgiw world")
let inputLength = attrStr.string.characters.count
let searchString = "world"
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
if (range.location != NSNotFound) {
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
textView.attributedText = attrStr
}
}
}

For Multiple Strings, You can do like this SWIFT 3

func textViewDidChange(_ textView: UITextView) {
let attrStr = NSMutableAttributedString(string: txtview.text)
let inputLength = attrStr.string.characters.count
let searchString : NSArray = NSArray.init(objects: "hello","world")
for i in 0...searchString.count-1
{

let string : String = searchString.object(at: i) as! String
let searchLength = string.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
range = (attrStr.string as NSString).range(of: string, options: [], range: range)
if (range.location != NSNotFound) {
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
textView.attributedText = attrStr
}
}
}
}

OBJECTIVE C

For Multiple Strings, You can do like this

-(void)textViewDidChange:(UITextView *)textView
{
NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc]initWithString:textView.text];
NSUInteger characterCount = [attstr length];
NSArray *arr = [[NSArray alloc]initWithObjects:@"football",@"player",nil];

for (int i=0; i
NSUInteger searchlength = [[NSString stringWithFormat:@"%@",[arr objectAtIndex:i]] length];
NSRange range1 = NSMakeRange(0, attstr.length);

while (range1.location != NSNotFound) {
range1 =[attstr.string rangeOfString:[NSString stringWithFormat:@"%@",[arr objectAtIndex:i]] options:0 range:range1];
if (range1.location !=NSNotFound) {
[attstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range1.location, searchlength)];
[attstr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:range1];
range1 = NSMakeRange(range1.location + range1.length, characterCount -(range1.location + range1.length));
textView.attributedText = attstr;
}
}
}

Is it possible to change selection color in UITextView iOS?

Yes, you can change text selection color using tintColor property of UITextView.
Use this code to get the expected output.

self.textView.tintColor = .red

Also, You can do this from the storyboard, see the following image.

Sample Image
Sample Image

Change textColor of a UITextView in Swift

I ended up deleting the UITextField in the Storyboard and putting a new one. I connected it to the ViewController with an @IBOutlet as before. I then went to 'Product' and 'Clean'. Afterwards I ran my my project and it worked fine. I still had the newly added UITextView called codeText assigned to the UITextFieldDelegate and works beautifully. Must have just had a bug in it and needed to start fresh.

How to change color of a word in UITextView?

I solve the problem. I created subclass of UILable and UITextView used core text (CATextLayer) as a layer on label/textview and NSAttributedString will store all the information about the font and color

If i wanted to change the color of a specific word entered in textview, How would i do that?

You will have to use attributed text for your text view and then use the textView(textView: UITextView, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool method, which will be triggered whenever the text in the text view's text changes. Apply your own logic in there as to what range the colored text will fall into and how that will happen...

Make sure your controller conforms to the UITextViewDelegate protocol and make the textView's delegate your controller.

Demonstration:

class ViewController: UIViewController, UITextViewDelegate {

@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()

self.textView.delegate = self // important! Otherwise the textView will not know where to call the delegate functions!
}

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

// first make sure that the text field is the one we want to actually change
if textView == self.textView{

let nsString = textView.text as NSString // we explicitly cast the Swift string to NSString so that we can use rangeOfString for example
let stringLength = textView.text.characters.count
// Arbitrarily check if the string in the text field is not empty
// Apply your own logic for when to update the string
if stringLength > 0{

let text = NSMutableAttributedString(string: textView.text)
// Currently the range is assumed to be the whole text (the range covers the whole string)
// You'll have to apply your own logic here
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, stringLength))

textView.attributedText = text

}
}
return true

}

}

For example, instead of using the above to color the whole text

text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, stringLength))

Color the first occurence of "hello" in red:

text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: nsString.rangeOfString("hello"))

Note that I explicitly cast the textView's text to NSString so that we can use the range functions such as (rangeOfString())



Related Topics



Leave a reply



Submit