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

Posted

技术标签:

【中文标题】在单个标签中使用多种字体颜色【英文标题】:Use multiple font colors in a single label 【发布时间】:2015-02-27 23:26:24 【问题描述】:

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

如果以文本“你好,你好吗”为例,“你好”是蓝色的,“你好吗”是绿色的?

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

【问题讨论】:

尝试使用 UILabel 的属性文本属性。 ***.com/questions/3586871/… 您想在字符串中添加范围颜色 【参考方案1】:

Reference from here.

首先初始化你的 NSStringNSMutableAttributedString,如下所示。

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

输出

多种颜色

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

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

多色输出

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

【讨论】:

能否添加两个范围属性,如果不能,我该如何解决? 感谢您的回答。就我而言,我从 API 中连续获取了两个用户名。我想给第二个名字上色,所以我不知道句子的长度。这种情况有什么解决办法吗?非常感谢。【参考方案2】:

对于@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

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

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

【讨论】:

【参考方案3】:

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

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)

结果:

【讨论】:

@Krunal 如何修改它以支持多个字符串来更改颜色...?我有一个长字符串,下面的标题有------------,但上面的代码工作正常,但它只为找到的第一个着色。这可以修改为将所有 --------- 字符串变为某种颜色....?谢谢。 这对这样的文本不起作用:“flow***”它只会改变第一个流,但我们需要最后一个,如何实现?【参考方案4】:

Swift 4 的更新答案

您可以轻松地使用 UILabel 的属性文本属性中的 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")
    

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

【讨论】:

我收到此错误消息:无法使用类型为 '(data: NSData, options: [String : String], documentAttributes: _, error: _) 的参数列表调用类型 'NSAttributedString' 的初始化程序' Swift 2 有变化。请查看我更新的答案。【参考方案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

【讨论】:

【参考方案6】:

我喜欢这种方式

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) 

【讨论】:

感谢这个简单的。【参考方案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

甚至对于单线

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

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

【讨论】:

【参考方案8】:

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

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

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

    

这个供使用

override func viewDidLoad() 
        super.viewDidLoad()

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

    

【讨论】:

【参考方案9】:

利用NSMutableAttributedString

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

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

【讨论】:

【参考方案10】:

斯威夫特 3.0

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

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

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

【讨论】:

【参考方案11】:

如果你想在你的应用程序中多次使用它,你可以创建 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】:

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)

【讨论】:

【参考方案13】:

使用 cocoapod Prestyler:

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

【讨论】:

【参考方案14】:

使用 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")
            

【讨论】:

【参考方案15】:

这是 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 - 样式应该是应用程序,“0”作为字符串的开头或某个有效值作为字符串的字符位置 length:Int - 从位置到此样式适用的字符数。

其他方式消费:

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

输出:

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

【讨论】:

【参考方案16】:
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
    

【讨论】:

【参考方案17】:

为了在 swift 低版本中使用此 NSForegroundColorAttributeName,您可以得到未解决的标识符问题,将上述更改为 NSAttributedStringKey.foregroundColor

             swift lower version                swift latest version

即,NSForegroundColorAttributeName == NSAttributedStringKey.foregroundColor

【讨论】:

【参考方案18】:

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

结果

【讨论】:

以上是关于在单个标签中使用多种字体颜色的主要内容,如果未能解决你的问题,请参考以下文章

具有多种文本颜色的文本视图android [重复]

html网页怎么设置字体颜色

html中改变字体颜色的代码怎么写

html中改变字体颜色的代码怎么写

html怎么改变字体大小和颜色

js设置字体颜色