如何根据结果更改文本标签颜色?

How to change the text label color according to its result?

我的应用程序正在显示一些分数结果,我想根据结果添加从红色到绿色的分数标签颜色变化:

self.scoreLabel.text = "\(total100)/100"

最简单的实现方式是什么?

提前致谢

您需要使用属性字符串

let myMutableString = NSMutableAttributedString(string: "\(total100)/100", attributes: [NSAttributedString.Key.font:UIFont(name: "Georgia", size: 18.0)!])
        myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:7,length:3))
    self.scoreLabel.attributedText = myMutableString

结果改变时调用此函数。

func setTextColor(score: Int){
    if score < 34 {
        self.scoreLabel.textColor = .red
    }else {
        self.scoreLabel.textColor = .green
    }
}