字符串的颜色部分

Color Part of String

我试图在 Swift5 中使用以下代码为字符串的一部分着色,问题是字符串是一个变量并且尚不存在,因此代码不起作用的原因。

代码使用存在的字符串工作:

let main_string = "Headline 5"
let string_to_color = "5"

但这不起作用:

let main_string = "Headline "
let string_to_color = "\(stringTime) min" //stringTime is a string of a number, for example "21"


let range = (main_string as NSString).range(of: string_to_color)

let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)

 self.Label.attributedText = attribute

知道如何让它在作为变量的字符串中着色并将其添加到我的字符串中吗?

对于这个例子,我有一个每秒触发的计时器,然后在显示的字符串中间建立一个带有递增计数器变量的字符串 - 这符合您的需要吗?

class ViewController: UIViewController {

@IBOutlet weak var lblDisplay: UILabel!
var timer : Timer!
var timerLoop : Int = 0


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
}

@objc func timerFired()
{
    timerLoop += 1

    let main_string = "First part \(timerLoop) second part"
    let string_to_color = "\(timerLoop)" //stringTime is a string of a number, for example "21"


    let range = (main_string as NSString).range(of: string_to_color)

    let attribute = NSMutableAttributedString.init(string: main_string)
    attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)

     self.lblDisplay.attributedText = attribute
}

}