天天看點

html label修改字型顔色,Swift label文字顯示不同顔色(字型)

根據 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)!])

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

// set label Attribute

labName.attributedText = myMutableString

super.viewDidLoad()

}

2. 使用 html 文本設定每段文本

Swift4:

let htmlString = "This is some text!"

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

}

3. 單獨設定每段的文本, 再拼接

Swift4:

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