Search code examples
iosswiftxcodenstimernsattributedstring

Reverse Time Label


I am looking for label which can give me functionality to count down reverse timer. I know there are Timer available to to count down, but I want reverse count down with Days, Hours, Minutes, Seconds like as following image.

Can anyone tell me how to implement this like as following image ?

enter image description here

Help will be appreciated. Thank You.


Solution

  • First you need to create an NSAttributedString with your time format requeriments something like this

    func timeLeftExtended(date:Date) ->NSAttributedString{
    
        let cal = Calendar.current
        let now = Date()
        let calendarUnits:NSCalendar.Unit = [NSCalendar.Unit.day, NSCalendar.Unit.hour, NSCalendar.Unit.minute, NSCalendar.Unit.second]
        let components = (cal as NSCalendar).components(calendarUnits, from: now, to: date, options: [])
    
        let fullCountDownStr = "\(components.day!.description)d " + "\(components.hour!.description)h " + "\(components.minute!.description)m " + "\(components.second!.description)s "
    
        let mutableStr = NSMutableAttributedString(string: fullCountDownStr, attributes: [NSAttributedStringKey.foregroundColor:UIColor.white])
    
        for (index,char) in mutableStr.string.enumerated()
        {
            if(char == "d" || char == "h" || char == "m" || char == "s")
            {
                mutableStr.removeAttribute(NSAttributedStringKey.foregroundColor, range: NSMakeRange(index, 1))
                mutableStr.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.lightGray], range: NSMakeRange(index, 1))
            }
        }
    
        return mutableStr
    }
    

    After that you need to declare the label where you want to update your time left

    @IBOutlet weak var lblTimeRemaining: UILabel!
    

    And add a timer and a flag to know when your timer is working

    fileprivate var timeWorking : Bool = false
    var timer:Timer?
    

    Here we setup our timer

    func setupWith()
    { 
        if(!timeWorking)
        {
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateCountDown), userInfo: nil, repeats: true)
            self.timeWorking = true
        }
    
    }
    

    This method will be executed 1 time every second to update our count

    @objc func updateCountDown()
    {
        self.lblTimeRemaining.attributedText = self.timeLeftExtended(date:Date.distantFuture)
    }
    

    RESULT

    enter image description here