How to Change Colour of the Certain Words in Label - Swift 3

How to change colour of the certain words in label - Swift 3

Use NSMutableAttributedString to apply colors for different words in a string.
Try this, there are already lot of similar questions have the answers in SO.

let myLabel = UILabel()
var stringOne = "Swift 3 has come"
let stringTwo = "has"

let range = (stringOne as NSString).range(of: stringTwo)

let attributedText = NSMutableAttributedString.init(string: stringOne)
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: range)
myLabel.attributedText = attributedText

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))

Change color of a certain word in UILabel

Try this, your attributed string has no value when you try get the range of the string. You got to give the attributed string a string value before that. You

  let descriptionLabel: UILabel = {

let label = UILabel()

// String variable containing the text.
let fullString = "mehmet alper tabak"

// Choose wwhat you want to be colored.
let coloredString = "alper"

// Get the range of the colored string.
let rangeOfColoredString = (fullString as NSString).range(of: coloredString)

// Create the attributedString.
let attributedString = NSMutableAttributedString(string:fullString)
attributedString.setAttributes([NSForegroundColorAttributeName: UIColor.red],
range: rangeOfColoredString)
label.attributedText = attributedString
return label
}()

descriptionLabel.frame = CGRect(x: 50, y: 50, width: 140, height: 100)
self.view.addSubview(descriptionLabel)

Or you can do an extension of UILabel.

  extension UILabel {

func colorString(text: String?, coloredText: String?, color: UIColor? = .red) {

let attributedString = NSMutableAttributedString(string: text!)
let range = (text! as NSString).range(of: coloredText!)
attributedString.setAttributes([NSForegroundColorAttributeName: color!],
range: range)
self.attributedText = attributedString
}

To use it.

      self.testLabel.colorString(text: "mehmet alper tabak",
coloredText: "alper")

How I can change text color for every 5 first words in label?

It's more efficient to get the index of the end of the 5th word and add color and font once for the entire range.

And you are strongly discouraged from bridging String to NSString to get a subrange from a string. Don't do that. Use native Swift Range<String.Index>, there is a convenience API to convert Range<String.Index> to NSRange reliably.

private func setMessageText(text: String) {
let components = text.components(separatedBy: .whitespacesAndNewlines)
let words = components.filter { !$0.isEmpty }

if words.count >= 5 {
let endOf5thWordIndex = text.range(of: words[4])!.upperBound
let nsRange = NSRange(text.startIndex..<endOf5thWordIndex, in: text)

let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttributes([.foregroundColor : Colors.TitleColor, .font : Fonts.robotoBold14], range: nsRange)
label.attributedText = attributedString
} else {
label.text = text
}
}

An alternative – more sophisticated – way is to use the dedicated API enumerateSubstrings(in:options: with option byWords

func setMessageText(text: String) {

var wordIndex = 0
var attributedString : NSMutableAttributedString?
text.enumerateSubstrings(in: text.startIndex..., options: .byWords) { (substring, substringRange, enclosingRange, stop) in
if wordIndex == 4 {
let endIndex = substringRange.upperBound
let nsRange = NSRange(text.startIndex..<endIndex, in: text)
attributedString = NSMutableAttributedString(string: text)
attributedString!.addAttributes([.foregroundColor : Colors.TitleColor, .font : Fonts.robotoBold14], range: nsRange)
stop = true
}
wordIndex += 1
}

if let attributedText = attributedString {
label.attributedText = attributedText
} else {
label.text = text
}
}

Is it possible to set a different colour for one character in a UILabel?

You can use NSMutableAttributedString.
You can set specific range of your string with different color, font, size, ...

E.g:

 var range = NSRange(location:2,length:1) // specific location. This means "range" handle 1 character at location 2

attributedString = NSMutableAttributedString(string: originalString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
// here you change the character to red color
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
label.attributedText = attributedString

Ref: Use multiple font colors in a single label - Swift

You can change a lot of attribute of String.
Ref from apple: https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html

Use multiple font colors in a single label

Reference from here.

First of all initialize of you NSString and NSMutableAttributedString as below.

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()

In ViewDidLoad

override func viewDidLoad() {

myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
// set label Attribute
labName.attributedText = myMutableString
super.viewDidLoad()
}

OUTPUT

Sample Image

MULTIPLE COLOR

Add the line code below in your ViewDidLoad to get multiple colors in a string.

 myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))

Multiple color OUTPUT

Sample Image

Swift 4

var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))

Swift 5.0

 var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))

How to set textColor of UILabel in Swift

The easiest workaround is create dummy labels in IB, give them the text the color you like and set to hidden.
You can then reference this color in your code to set your label to the desired color.

yourLabel.textColor = hiddenLabel.textColor

The only way I could change the text color programmatically was by using the standard colors, UIColor.white, UIColor.green...



Related Topics



Leave a reply



Submit