Сначала вам нужно создать 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)
}
РЕЗУЛЬТАТ
person
Reinier Melian
schedule
02.03.2018