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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27728466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:12:03  来源:igfitidea点击:

Use multiple font colors in a single label

iosswiftuilabelnsattributedstringtextcolor

提问by Justin Rose

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

有没有办法在 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?

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

回答by Kirit Modi

Reference from here.

从这里参考。

First of all initialize?of you NSStringand NSMutableAttributedStringas below.

首先初始化?你的NSStringNSMutableAttributedString如下。

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

In ViewDidLoad

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

enter image description here

MULTIPLE COLOR

多色

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

在您的 ViewDidLoad 中添加下面的行代码以获取字符串中的多种颜色。

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

Multiple color OUTPUT

多色输出

enter image description here

enter image description here

Swift 4

斯威夫特 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))

回答by Keyur Hirani

For @Hems Moradiya

对于@Hems Moradiya

enter image description here

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

斯威夫特 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

斯威夫特 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

回答by Krunal

Swift 4

斯威夫特 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

enter image description here

回答by rakeshbs

Updated Answer for Swift 4

Swift 4 的更新答案

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

你可以很容易地在 UILabel 的 attributesText 属性中使用 html 来轻松地进行各种文本格式设置。

 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

enter image description here

Updated Answer for Swift 2

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

回答by mathielo

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

使用rakeshbs的答案在 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 .attributedStringFromHtmlattribute for all Strings throughout your whole application.

扩展的好处是您将拥有整个应用程序中.attributedStringFromHtml所有Strings 的属性。

回答by jithin

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) 

回答by Ridho Octanio

UPDATE for SWIFT 5

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

斯威夫特 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)

    }

回答by Paul Wasilewski

Here a solution for Swift 5

这是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

enter image description here

回答by Cilvet

Swift 3.0

斯威夫特 3.0

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

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

result:

result:

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

对于更多颜色,您可以继续向可变字符串添加属性。更多例子在这里

回答by Shamsudheen TK

Make use of NSMutableAttributedString

利用 NSMutableAttributedString

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

enter image description here

enter image description here

See more details here swift-using-attributed-strings

在此处查看更多详细信息swift-using-attributed-strings