欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UITextView 设置同一段文字,多个文字颜色

程序员文章站 2022-06-01 14:22:20
...

利用NSMutableAttributedString实现

预览图如下
UITextView 设置同一段文字,多个文字颜色

  • 创建 NSAttributedString
 let subjectString1 = NSAttributedString(string: "CLUD:  ", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.init(name: "Quicksand-Bold", size: ScreenUtil.getRelativeWidth(22))])
 var subjectString2 = NSAttributedString(string: "HAVE FUN", attributes: [NSAttributedStringKey.foregroundColor: UIColor.init(hexString: "#FBE85B"), NSAttributedStringKey.font: UIFont.init(name: "Quicksand-Bold", size: ScreenUtil.getRelativeWidth(22))])
  • 创建 NSMutableAttributedString
var message = NSMutableAttributedString(attributedString: subjectString1)
        message.append(subjectString2)
  • 设置 attributedText
var textView = UITextView()
textView.attributedText = message