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;
}
}
}
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
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
UITextView Color of the selected text
If you just want to change the selected range of the string, you must change the attributedText
property. You can do something like:
@IBAction func didTapButton(sender: UIButton) {
let range = textView.selectedRange
let string = NSMutableAttributedString(attributedString: textView.attributedText)
let attributes = [NSForegroundColorAttributeName: UIColor.redColor()]
string.addAttributes(attributes, range: textView.selectedRange)
textView.attributedText = string
textView.selectedRange = range
}
If you want to change the whole string, you can use the technique suggested by CeceXX.
@IBAction func didTapButton(sender: UIButton) {
textView.textColor = UIColor.redColor()
}
How can I change style of some words in my UITextView one by one in Swift?
Use a timer. Stash matches in a property. Stash the base unhighlighted attributed string in a property. Now have your timer highlight the first match and call itself again in 1 second, highlighting up to the second match and repeat until there are no matches left.
func highlight (to index: Int = 0) {
guard index < matches.count else {
return
}
let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor]
let attributedString = NSMutableAttributedString(attributedString: storedAttributedString)
for i in 0..< index {
let matchRange = matches[i].rangeAt(0)
attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange)
}
self.attributedText = attributedString
let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
self.highlight(to: index + 1)
}
}
Swiftui using UITextVIew for hyperlink but can't change text color
Here is what I meant. Tested with Xcode 13.3 / iOS 15.4
*Red color used for better visibility
func updateUIView(_ uiView: UITextView, context: Context) {
let attributedOriginalText = NSMutableAttributedString(string: text)
for (urlString, hyperLink) in links {
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
attributedOriginalText.addAttribute(.link, value: urlString, range: linkRange)
}
let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
attributedOriginalText.addAttribute(.foregroundColor, value: UIColor.red, range: fullRange)
uiView.attributedText = attributedOriginalText
uiView.linkTextAttributes = [
.underlineStyle : NSUnderlineStyle.single.rawValue,
.foregroundColor: UIColor.red
]
Can I change the color of auto detected links on UITextView?
On iOS 7 you can set the tintColor
of the UITextView
. It affects the link color as well as the cursor line and the selected text color.
iOS 7 also added a new property to UITextView
called linkTextAttributes
which would appear to let you fully control the link style.
iOS Swift Change Particular Text Color Inside Label Programatically
You can use following code to search in string
//Text need to be searched
let SearchAttributeText = "the"
//Store label text in variable as NSString
let contentString = lblContent.text! as NSString
//Create range of label text
var rangeString = NSMakeRange(0, contentString.length)
//Convert label text into attributed string
let attribute = NSMutableAttributedString.init(string: contentString as String)
while (rangeString.length != NSNotFound && rangeString.location != NSNotFound) {
//Get the range of search text
let colorRange = (lblContent.text?.lowercased() as! NSString).range(of: SearchAttributeText, options: NSString.CompareOptions(rawValue: 0), range: rangeString)
if (colorRange.location == NSNotFound) {
//If location is not present in the string the loop will break
break
} else {
//This line of code colour the searched text
attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red , range: colorRange)
lblContent.attributedText = attribute
//This line of code increment the rangeString variable
rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length))
}
}
The below line of code update the range by incrementing the location
and length
parameter of NSRange
rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length))
How get textview attributed text?
You need to get the attributedText
from the UITextView and then append new text to it like:
let existingText = myTextView.attributedText
let mutableText = NSAttributedString(attributedString: existingText)
// Then add your text
Check NSMutableAttributedString docs for how to do the last part.
Related Topics
Uibutton with Single Press and Long Press Events Swift
Load a .Tmx (Tiled Map) in Sprite Kit
Submitting iOS App to App Store Application Identifier Invalid
Error: Uitableview Jump to Top with Uitableviewautomaticdimension
Open App from Sms with My Url Scheme as a Link
Why Is Uiwebview Cangoback=No in iOS7
iOS Permission Alerts - Removing or Suppressing
How to Group Array of Objects by Date in Swift
Uiscrollview with iOS Auto Layout Constraints: Wrong Size for Subviews
Get User Swiping Direction in Uipageviewcontroller
How to Change Pagetabview Programmatically in iOS 14, Swiftui 2
iOS 9 Cloudkit: Query Does Not Return Anything While Connected to Cellular Network
Switching from Xcode3 to Xcode4 - Can't Load Programs Onto Older Ipod Touch
Xcode 7 Crash: [Nslocalizablestring Length] 30000
Play a Video from Youtube in a Avplayerviewcontroller in Swift