答案 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 强>