Uitextview Change Text Color of Specific Text

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

Change font color of UITextView

I just tried that and I had no problems. I set up a button that called [myTextView setTextColor:[UIColor redColor]];

After typing a bit with black text color, I pressed the button, and everything turned red. Then I continued typing, all in red.

Are you using setTextColor: to do this also?

How do you change the color of text in a UITextView?


yourTextView.textColor = [UIColor redColor];

Looking up UITextView in the documentation gives this immediately. ;-)

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..<chars.count {
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

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<arr.count; 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;
}
}
}

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.

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.

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

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



Related Topics



Leave a reply



Submit