参考这里。
首先初始化你NSString and NSMutableAttributedString如下。
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
In 查看是否加载
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()
}
OUTPUT
多种颜色
在 ViewDidLoad 中添加下面的行代码以获取字符串中的多种颜色。
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))
多色输出
Swift 4
var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))
雨燕5.0
var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))