Swiftlabel文字显示不同颜色(字体)

更新时间:2023-05-09 05:10:00 阅读: 评论:0

Swiftlabel⽂字显⽰不同颜⾊(字体)
根据  ⼤概有三种⽅法:
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: dColor(), range: NSRange(location:2,length:4))
// t label Attribute
labName.attributedText = myMutableString
super.viewDidLoad()
}
2. 使⽤ html ⽂本设置每段⽂本
Swift4:
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")
}
3. 单独设置每段的⽂本, 再拼接
Swift4:
let attrs1 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : ]
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)
lf.lblText.attributedText = attributedString1

本文发布于:2023-05-09 05:10:00,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/561891.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:改变   设置   字体
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图