Use multiple font colors in a single label

白昼怎懂夜的黑 提交于 2020-01-08 17:09:10

问题


Is there a way to use two, or even three font colors in a single label in iOS?

If the text "hello, how are you" were used as an example, the "hello," would be blue, and the "how are you" would be green?

Is this possible, it seems easier than creating multiple labels?


回答1:


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

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

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



回答2:


For @Hems Moradiya

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



回答3:


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:




回答4:


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

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



回答5:


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.




回答6:


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:5,length:4))
        attributedText = attText

    }
}

and this for use

override func viewDidLoad() {
        super.viewDidLoad()

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

    }



回答7:


Make use of NSMutableAttributedString

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

See more details here swift-using-attributed-strings




回答8:


I liked it this way

let yourAttributes = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFontOfSize(15)]
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.systemFontOfSize(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.appendAttributedString(partOne)
combination.appendAttributedString(partTwo) 



回答9:


Swift 3.0

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

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

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




回答10:


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)



回答11:


Use cocoapod Prestyler:

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



回答12:


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




回答13:


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



回答14:


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:

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)




回答15:


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
    }



回答16:


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




回答17:


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



来源:https://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!