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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值