在一个标签中使用多种字体颜色

在 iOS 系统中,是否可以在一个标签中使用两种甚至三种字体颜色?

如果使用文本“ hello,how are you”作为例子,那么“ hello”应该是蓝色的,而“ how are you”应该是绿色的?

这是否可能,它似乎比创建多个标签更容易?

121051 次浏览

Make use of NSMutableAttributedString

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

enter image description here

See more details here swift-using-attributed-strings

Updated Answer for Swift 4

You can easily use html inside attributedText property of the UILabel to easily do various text formatting.

 let htmlString = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>"


let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString


} catch _ {
print("Cannot create attributed String")
}

enter image description here

Updated Answer for Swift 2

let htmlString = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>"


let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString


} catch _ {
print("Cannot create attributed String")
}

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

enter image description here

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

enter image description here

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

Used rakeshbs's answer to create an extension in Swift 2:

// StringExtension.swift
import UIKit
import Foundation


extension String {


var attributedStringFromHtml: NSAttributedString? {
do {
return try NSAttributedString(data: self.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch _ {
print("Cannot create attributed String")
}
return nil
}
}

Usage:

let htmlString = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>"
label.attributedText = htmlString.attributedStringFromHtml

Or even for one-liners

label.attributedText = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>".attributedStringFromHtml

The good thing about the extension is that you'll have .attributedStringFromHtml attribute for all Strings throughout your whole application.

For @Hems Moradiya

enter image description here

let attrs1 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.greenColor()]


let attrs2 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.whiteColor()]


let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)


let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)


attributedString1.appendAttributedString(attributedString2)
self.lblText.attributedText = attributedString1

Swift 4

    let attrs1 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.green]


let attrs2 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.white]


let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)


let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)


attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1

Swift 5

    let attrs1 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.green]


let attrs2 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.white]


let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)


let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)


attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1

I liked it this way

let yourAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]
let yourOtherAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25)]


let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)


let combination = NSMutableAttributedString()


combination.append(partOne)
combination.append(partTwo)

Swift 3 example using the HTML version.

let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}

Swift 3.0

let myMutableString = NSMutableAttributedString(
string: "your desired text",
attributes: [:])


myMutableString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.blue,
range: NSRange(
location:6,
length:7))

result:

For more colors you can just keep adding attributes to the mutable string. More examples here.

Here is the code which supports Latest version of Swift as on Mar 2017.

Swift 3.0

Here I have created a Helper class and method for the

public class Helper {


static func GetAttributedText(inputText:String, location:Int,length:Int) -> NSMutableAttributedString {
let attributedText = NSMutableAttributedString(string: inputText, attributes: [NSFontAttributeName:UIFont(name: "Merriweather", size: 15.0)!])
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0) , range: NSRange(location:location,length:length))
return attributedText
}
}

In the Method Parameters, inputText:String - your Text to be displayed in label location:Int - where the style should be application, "0" as start of the string or some valid value as character position of the string length:Int - From the location until how many characters this style is applicable.

Consuming in other method:

self.dateLabel?.attributedText = Helper.GetAttributedText(inputText: "Date : " + (self.myModel?.eventDate)!, location:0, length: 6)

Output:

enter image description here

Note: The UI Color can be defined color as UIColor.red or user defined colors as UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0)

func MultiStringColor(first:String,second:String) -> NSAttributedString
{
let MyString1 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.PUREBLACK]


let MyString2 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.GREENCOLOR]


let attributedString1 = NSMutableAttributedString(string:first, attributes:MyString1)


let attributedString2 = NSMutableAttributedString(string:second, attributes:MyString2)


MyString1.append(MyString2)


return MyString1
}

UPDATE for SWIFT 5

func setDiffColor(color: UIColor, range: NSRange) {
let attText = NSMutableAttributedString(string: self.text!)
attText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
attributedText = attText
}

SWIFT 3

In my code , i create an extension

import UIKit
import Foundation


extension UILabel {
func setDifferentColor(string: String, location: Int, length: Int){


let attText = NSMutableAttributedString(string: string)
attText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueApp, range: NSRange(location:location,length:length))
attributedText = attText


}
}

and this for use

override func viewDidLoad() {
super.viewDidLoad()


titleLabel.setDifferentColor(string: titleLabel.text!, location: 5, length: 4)


}

Swift 4

By using following extension function, you can directly set a color attribute to an attributed string and apply the same on your label.

extension NSMutableAttributedString {


func setColorForText(textForAttribute: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)


// Swift 4.2 and above
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)


// Swift 4.1 and below
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}


}

Try above extension, using a label:

let label = UILabel()
label.frame = CGRect(x: 60, y: 100, width: 260, height: 50)
let stringValue = "stackoverflow"


let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textForAttribute: "stack", withColor: UIColor.black)
attributedString.setColorForText(textForAttribute: "over", withColor: UIColor.orange)
attributedString.setColorForText(textForAttribute: "flow", withColor: UIColor.red)
label.font = UIFont.boldSystemFont(ofSize: 40)


label.attributedText = attributedString
self.view.addSubview(label)

Result:

enter image description here

for using this NSForegroundColorAttributeName in swift lower version you can get unresolved identifier issues change the above to NSAttributedStringKey.foregroundColor.

             swift lower version                swift latest version

i.e., NSForegroundColorAttributeName == NSAttributedStringKey.foregroundColor

Swift 4 UILabel Extension

In my case, I needed to be able to set different colors/fonts within labels frequently so I made a UILabel extension using Krunal's NSMutableAttributedString extension.

func highlightWords(phrases: [String], withColor: UIColor?, withFont: UIFont?) {


let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)


for phrase in phrases {


if withColor != nil {
attributedString.setColorForText(textForAttribute: phrase, withColor: withColor!)
}
if withFont != nil {
attributedString.setFontForText(textForAttribute: phrase, withFont: withFont!)
}


}


self.attributedText = attributedString


}

It can be used like this:

yourLabel.highlightWords(phrases: ["hello"], withColor: UIColor.blue, withFont: nil)
yourLabel.highlightWords(phrases: ["how are you"], withColor: UIColor.green, withFont: nil)

Use cocoapod Prestyler:

Prestyle.defineRule("*", Color.blue)
Prestyle.defineRule("_", Color.red)
label.attributedText = "*This text is blue*, _but this one is red_".prestyled()

Swift 4.2

    let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center


var stringAlert = self.phoneNumber + "로\r로전송인증번호를입력해주세요"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringAlert, attributes: [NSAttributedString.Key.paragraphStyle:paragraphStyle,  .font: UIFont(name: "NotoSansCJKkr-Regular", size: 14.0)])
attributedString.setColorForText(textForAttribute: self.phoneNumber, withColor: UIColor.init(red: 1.0/255.0, green: 205/255.0, blue: 166/255.0, alpha: 1) )
attributedString.setColorForText(textForAttribute: "로\r로전송인증번호를입력해주세요", withColor: UIColor.black)


self.txtLabelText.attributedText = attributedString

Result

Result

Here a solution for Swift 5

let label = UILabel()
let text = NSMutableAttributedString()
text.append(NSAttributedString(string: "stack", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]));
text.append(NSAttributedString(string: "overflow", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray]))
label.attributedText = text

enter image description here