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


88

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

如果以文本“ hello,您好”为例,则“ hello”为蓝色,而“您好”为绿色?

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


尝试使用UILabel的属性文本属性。stackoverflow.com/questions/3586871/...
rakeshbs

您要在字符串中添加“范围颜色”
Kirit Modi'1

Answers:


150

从这里参考。

首先,如下所示初始化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))

1
您可以添加两个范围属性吗?如果没有,该如何解决?
贾斯汀·罗斯

58

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

38

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

结果:

在此处输入图片说明


@Krunal如何修改它以支持多个字符串以更改颜色...?我有一个长字符串,标题下面有------------,但是上面的代码可以正常工作,但是它只会为第一个找到的颜色着色。可以将其修改为将所有---------字符串制成某种颜色吗?谢谢。
Omid CompSCI

这对于这样的文本是行不通的:“ flowstackoverflow”它只会更改第一个流程,但是我们需要最后一个流程,如何实现呢?
swift2geek

19

更新了Swift 4的答案

您可以轻松地使用UILabel的attributedText属性内的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")
}

2
我收到此错误消息:无法调用类型为'(data:NSData,options:[String:String],documentAttributes:_,error:_)'的参数列表的'NSAttributedString'类型的初始化程序
Qian Chen

2
Swift 2中有更改。请检查我更新的答案。
rakeshbs 2015年

9

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

在此处输入图片说明


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

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


6

我喜欢这样

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) 

感谢您的简单回答。
Nikhil Manapure

6

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)

    }


5

斯威夫特3.0

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

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

结果:

要获得更多颜色,您可以继续向可变字符串添加属性。这里有更多示例。


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)

1

使用cocoapod Prestyler

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

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

0

这是支持2017年3月最新版本的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-要在标签位置显示的文本:Int-应在其中应用样式的位置,“ 0”作为字符串的开头,或某个有效值作为字符串长度的字符位置:Int-从位置,直到此样式适用于多少个字符为止。

食用其他方法:

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

输出:

在此处输入图片说明

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


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
    }

0

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

             swift lower version                swift latest version

即,NSForegroundColorAttributeName == NSAttributedStringKey.foregroundColor


0

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

结果

结果

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.