According to normal string in iOS, There is not provide the facility of colorful string in iOS, but have a class NSAttributeString which have provide color of string facility. For formatting a part of a string, you need an attributed string
which specifies parts of the string formatted in different ways. In
this lesson we’ll learn how to work in attributed strings in Swift.
First of all you Setup new project, and take different label in the View Controller. Here I am taking six label and all label connects IBOutlet in ViewController.swift file.
Initializing an Attributed String
First of all initializing Attributed string, so adding below code in ViewDidLoad method.
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: myString as
String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
As above Code, The first string myString which want to colorful string, and second is NSMutableAttributedString add attribute.
Lable-1: Change the color of single string.
In the label an attributed string with the string myString and an attribute dictionary. Here we used an attribute named NSForegroundColorAttributeName as the key, and a UIColor.redColor() object as the value. and also passing range of which want to change NSRange(location:2,length:2) Build and run. Code as below of first label.
we used an attribute named NSFontAttributeName as the key, and a UIFont(name: "AmericanTypewriter-Bold", size: 18.0)! object as the value. and also passing range of which want to changeNSRange(location:5,length:5) Build and run. Code as below of first label.
Lable-4: Change the stroke color and width of string.
we used two attribute named NSStrokeColorAttributeName as the key, and a UIColor.blueColor() object as the value. NSStrokeWidthAttributeName as the key, and a "2" object as the value. and give the same range both adding attribute. Build and run. Code as below forth label.