I want to show countdown timer in UILabel but when I am updating the timer next sentence/ word position is getting changed. Complete sentence after timer is moving left, right.
I want to fix the width for timer(4:47) so that only timer value should update without changing position of any other word. Any Idea will be help full to fix this. I can't use three labels because text is multiline.
Here is the code I am using:
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {[weak self] timer in
self?.updateText()
if let time = self?.reservedTimeInSeconds, time < 0 {
timer.invalidate()
self?.reservedTimeInSeconds = 300
}
}
}
func updateText() {
let minutes: Int = self.reservedTimeInSeconds / 60
let seconds: Int = self.reservedTimeInSeconds % 60
let timer = String(format: "%d:%02d", minutes, seconds)
self.textLabel.text = "Price valid for: \(timer). All prices inclusive of 3% gst."
self.reservedTimeInSeconds -= 1
}
I tried using attributed string but no luck, this code somewhat working but when I trying to set custom font and font size its breaking.
func updateText() {
let minutes: Int = self.reservedTimeInSeconds / 60
let seconds: Int = self.reservedTimeInSeconds % 60
let timer = String(format: "%d:%02d", minutes, seconds)
let html = "<div>%@ <div style=\"color: %@;text-align: center;display: inline-block; overflow: hidden;\">%@</div>. %@</div>"
let htmlFilledString = String(format: html, "Price valid for: ", "green", timer, "All price inclusive of 3% gst. All price inclusive of 3% gst")
self.textLabel.attributedText = htmlFilledString.html2AttributedString
self.reservedTimeInSeconds -= 1
}
extension Data {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
extension String {
var html2AttributedString: NSAttributedString? {
return Data(utf8).html2AttributedString
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}