反向时间标签

问题描述 投票:4回答:1

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

谁能告诉我如何实现这个如下图像?

enter image description here

帮助将不胜感激。谢谢。

ios swift xcode nstimer nsattributedstring
1个回答
2
投票

首先,你需要创建一个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
    }

}

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

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

结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.