im trying to use the below code in Swift5 to color part of a string, problem is the string is a variable and doesn't exist yet, hence why the code doesn't work.
The code works using a string that exists:
let main_string = "Headline 5"
let string_to_color = "5"
This doesn't work however:
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
Any idea how I can make it work to color in a string that's a variable and add it to my string?
For this example, I have a timer which fires every second, and then build up a string with an incrementing counter variable in the middle of the displayed string - does this match what you need?
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
}
}