700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > html label修改字体颜色 Swift label文字显示不同颜色(字体)

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

时间:2020-05-20 05:31:45

相关推荐

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

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

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

var myString:NSString = "I AM KIRIT MODI"

var myMutableString = NSMutableAttributedString()

InViewDidLoad

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。