Swift label文字显示不同颜色(字体)

时间:2025-04-04 17:23:02

 根据 Stack Overflow 上的这篇文章 大概有三种方法:

1. 先设置整个 text 为 NSMutableAttributedString, 再使用 Range 设置要改变颜色(字体)的文本

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)!])
    (NSForegroundColorAttributeName, value: (), range: NSRange(location:2,length:4))
    // set label Attribute
     = myMutableString
    ()
}

2. 使用 html 文本设置每段文本

Swift4:

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

    let encodedData = (using: .utf8)!
    let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do {
        let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
         = attributedString

    } catch _ {
        print("Cannot create attributed String")
    }

3. 单独设置每段的文本, 再拼接

Swift4:

let attrs1 = [ : (ofSize: 18),  : ]

    let attrs2 = [ : (ofSize: 18),  : ]

    let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)

    let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)

    (attributedString2)
     = attributedString1