Updated 17 November 2023
Sometimes we need to manage multiple timers in UIView so if we recreate multiple timers then it will show wrong value so for this we need to create a single Timer class for every single UIView, for doing this we need to follow some steps:
1: Create an array of timers:
var timer = [Timer]()
2: Now in for loop where you creating multiple views here you have to append the timer and also the UILabel on which the value will show :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
if ((data.object(forKey: "mainDeal") as? NSArray)?.count)! > 0{ let dealofDayTime = UILabel(frame: CGRect(x: 10, y: Y, width: categoryBlock.frame.size.width - 20, height: 30)) dealofDayTime.textColor = UIColor.white dealofDayTime.tag = i dealofDayTime.textAlignment = .left dealofDayTime.font = UIFont(name: BOLDFONT, size: 14) dealofDayTime.text = formattedString categoryBlock.addSubview(dealofDayTime); var details = [String:AnyObject](); details = ["label":dealofDayTime]; self.timer.append(Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.runScheduledTask), userInfo: details, repeats: true)) } |
3: Now define the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
func runScheduledTask(_ runningTimer: Timer) { var dict = runningTimer.userInfo as! [String:AnyObject]; let label:UILabel = dict["label"] as! UILabel var remainingSeconds = dealOfTheDay.object(at: label.tag) as! Double; remainingSeconds -= 1 if remainingSeconds == 0 || remainingSeconds < 0{ runningTimer.invalidate() label.text = "" } else{ let formatter = DateComponentsFormatter() formatter.allowedUnits = [.day,.hour, .minute, .second] formatter.unitsStyle = .positional let formattedString = formatter.string(from: TimeInterval(remainingSeconds))! label.text = formattedString.uppercased() dealOfTheDay.replaceObject(at: label.tag, with: remainingSeconds) } } |
Note:
here “dealOfTheDay” is an array of interval time:
“dealOfTheDay” = [100,200,145….] so on
4: for reinitializing you need to do like that
1 2 3 4 5 |
for i in 0..<self.timer.count{ let t:Timer = timer[i]; t.invalidate() } self.timer = [Timer]() |
That’s All
For any queries, feel free to ask.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.