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

时间:2015-01-01 05:20:48

标签: ios swift uilabel nsattributedstring textcolor

有没有办法在iOS中的单个标签中使用两种甚至三种字体颜色?

如果文字"你好,你好吗"用作例子,"你好,"会是蓝色的,"你好吗"会是绿色的吗?

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

18 个答案:

答案 0 :(得分:121)

首先初始化你 NSString NSMutableAttributedString ,如下所示。

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

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

**你的输出:**

enter image description here

MULTIPLE COLOR

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

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

多种颜色输出

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

答案 1 :(得分:36)

@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

答案 2 :(得分:20)

Swift 4

通过使用以下扩展功能,您可以直接将颜色属性设置为属性字符串,并在标签上应用该属性。

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

}

使用标签尝试上述扩展名:

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)

<强>结果:

enter image description here

答案 3 :(得分:18)

更新了Swift 4的答案

您可以轻松地在UILabel的attributionText属性中使用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

更新了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")
}

答案 4 :(得分:7)

使用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
    }
}

用法:

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

甚至 one-liners

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

扩展程序的好处在于,在整个应用程序中,您将拥有.attributedStringFromHtmlString属性。

答案 5 :(得分:5)

利用NSMutableAttributedString

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

enter image description here

在此处查看更多详情swift-using-attributed-strings

答案 6 :(得分:5)

Swift 3.0

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

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

result:

对于更多颜色,您可以继续向可变字符串添加属性。 更多示例here

答案 7 :(得分:4)

我喜欢这种方式

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) 

答案 8 :(得分:4)

SWIFT 3

在我的代码中,我创建了一个扩展

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

    }
}

这个用于

override func viewDidLoad() {
        super.viewDidLoad()

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

    }

答案 9 :(得分:1)

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

答案 10 :(得分:1)

Swift 4 UILabel扩展

就我而言,我需要能够经常在标签内设置不同的颜色/字体,因此我使用Krunal的NSMutableAttributedString扩展名进行了UILabel扩展。

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

}

可以这样使用:

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

答案 11 :(得分:0)

如果您想在应用程序中多次使用它,则只需创建UILabel的扩展即可,它会变得更加简单:-

快捷键5

extension UILabel {
    func setSpannedColor (fullText : String , changeText : String ) {
        let strNumber: NSString = fullText as NSString
        let range = (strNumber).range(of: changeText)
        let attribute = NSMutableAttributedString.init(string: fullText)
        attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
        self.attributedText = attribute
    }
}

使用标签:-

yourLabel = "Hello Test"
yourLabel.setSpannedColor(fullText: totalLabel.text!, changeText: "Test")

答案 12 :(得分:0)

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

答案 13 :(得分:0)

使用可可足纲Prestyler

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

答案 14 :(得分:0)

要在较低版本中使用此 NSForegroundColorAttributeName ,您可能会遇到未解决的标识符问题,请将上面的内容更改为 NSAttributedStringKey.foregroundColor

             swift lower version                swift latest version

NSForegroundColorAttributeName == NSAttributedStringKey.foregroundColor

答案 15 :(得分: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
    }

答案 16 :(得分:0)

以下是2017年3月支持最新版Swift 的代码。

Swift 3.0

这里我为

创建了一个Helper类和方法
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
    }
}

在方法参数中 inputText:String - 要在标签中显示的文本 location:Int - 样式应该应用的地方,&#34; 0&#34;作为字符串的开头或一些有效值作为字符串的字符位置 length:Int - 从该位置直到此样式适用的字符数。

以其他方式消费:

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

输出:

enter image description here

注意:UI颜色可以定义为UIColor.red或用户定义的颜色为UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0)

答案 17 :(得分:0)

使用HTML版本的Swift 3示例。

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