反向时间标签

时间:2018-03-02 08:07:47

标签: ios swift xcode nstimer nsattributedstring

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

有谁能告诉我如何实现这个如下图所示?

enter image description here

帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

首先,您需要创建一个NSAttributedString,其中包含您的时间格式requeriments

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
    }

}

此方法将每秒执行一次以更新我们的计数

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

<强> RESULT

enter image description here