代码之家  ›  专栏  ›  技术社区  ›  Sagar Chauhan

反转时间标签

  •  4
  • Sagar Chauhan  · 技术社区  · 7 年前

    我正在寻找标签,可以给我倒计时倒计时功能。我知道有计时器可以倒计时,但我想用天、小时、分钟、秒倒计时,如下图所示。

    有人能告诉我如何像下图一样实现这一点吗?

    enter image description here

    我们将不胜感激。非常感谢。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Reinier Melian    7 年前

    首先,您需要创建 NSAttributedString 用你的时间格式要求如下

    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
    }
    

    之后,您需要声明要更新剩余时间的标签

    @IBOutlet weak var lblTimeRemaining: UILabel!
    

    并添加计时器和标志,以了解计时器何时工作

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

    我们在这里设置计时器

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

    此方法将每秒执行1次以更新计数

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

    结果

    enter image description here