在标签中设置日期时间并设置动画时间

时间:2018-07-08 06:10:31

标签: swift date timer uilabel

我很难完成某件事。我正在使用Firebase作为数据库。用户创建新的民意测验帖子时,他们还必须设置一个到期日期。在应用程序本身中,我必须在UILabel中将到期日期显示为计时器(或倒计时?),以显示应禁用的投票剩余时间。

这是我到目前为止所拥有的:

extension Date {


func offsetFromNow() -> String {
       let formatter = DateComponentsFormatter()
       formatter.allowedUnits = [.day, .hour, .minute, .second]
       formatter.unitsStyle = .abbreviated
       return formatter.string(from: Date(), to: self)!
   }
}

class PostPollCVCell: UICollectionViewCell {
    var seconds = 60 
    var timer = Timer()
    var isTimerRunning = false
    func updateView() {
        if let expirationTimeInt = post?.pollExpirationTime {
            let expirationDate = Date(timeIntervalSince1970: Double(expirationTimeInt))
            self.pollExpirationDate.text = "poll ends in: " + expirationDate.offsetFromNow()
        }
    }

   func runTimer() {
   timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)
    }

    @objc func updateTimer() {
        seconds -= 1     //This will decrement(count down)the days, hours, min and seconds.
      // pollExpirationDate.text = Update the label with the total time left
    }
}

上面的代码唯一要做的就是简单地获取日期并将pollExpirationDate.text设置为基本上是什么时间。输出格式如下:

  

3d 3h 34min 5s

我该怎么做,不知道该怎么做(需要帮助的代码):

  1. 我必须确保时间不为负。现在,它只是显示时间,即使它是负数也是如此。如果时间为负数,则表示 pollExpirationDate UILabel只能说民意调查已经结束,禁用投票选项(UIButton)并显示带有结果(现在,我不希望您这样做,这时还没有设置,我只需要知道我应该在哪里运行此代码,仅此而已)

  2. 我正在从FirebaseDatabase下载日期并设置UILabel,但是我不知道如何创建应该为{{1}设置动画的计时器(或倒计时) } pollExpirationDate(剩余时间)

  3. 当倒计时达到0秒时,应禁用投票(时间已到期)

我从未做过任何事情,因此非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在类中全局创建两个变量,以检查计时器的状态为工作还是暂停/停止。

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

然后,创建一种方法来获取与您所描述的相同的每个日期部分。

func timeLeftExtended(date:Date) -> NSAttributedString {

    let cal = Calendar.current
    let now = Date()
    let calendarUnits : NSCalendar.Unit = [.day, .hour, .minute, .second]
    let components = (cal as NSCalendar).components(calendarUnits, from: now, to: date, options: [])

    let fullCountDownStr = ""

    if(components.day!.description == "0" || components.day!.description == "00") {

        // This will display hour, minute, and second
        fullCountDownStr = "\(components.hour!.description)h " + "\(components.minute!.description)m " + "\(components.second!.description)s "

    } else if (components.day!.description == "0" || components.day!.description == "00") && (components.hour!.description == "0" || components.hour!.description == "00") {

        // This will display minute and second
        fullCountDownStr = "\(components.minute!.description)m " + "\(components.second!.description)s "

    } else if (components.day!.description == "0" || components.day!.description == "00") && (components.hour!.description == "0" || components.hour!.description == "00") && (components.minute!.description == "0" || components.minute!.description == "00") {

        // This will display second only
        fullCountDownStr = "\(components.second!.description)s "

    } else {

        // This will display day, hour, minute, second
        fullCountDownStr = "\(components.day!.description)d " + "\(components.hour!.description)h " + "\(components.minute!.description)m " + "\(components.second!.description)s "

    }

    let mutableStr = NSMutableAttributedString(string: fullCountDownStr, attributes: [.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([.foregroundColor : UIColor.white], range: NSMakeRange(index, 1))
            mutableStr.addAttributes([.font: UIFont.systemFont(ofSize: 12)], range: NSMakeRange(index, 1))
        }
    }

    return mutableStr
}

这会给我3d 3h 34min 5s格式的日期。

为make Timer的计数器设置动画并调用此方法。

func setupTimer() {

    if let expirationTimeInt = post?.pollExpirationTime {
        let expirationDate = Date(timeIntervalSince1970: Double(expirationTimeInt))

        if expirationDate == Date() {
            self.pollExpirationDate.text = "expirationDate is Today's date"
        } else if date! > Date() {
            if(!timeWorking) {
                timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateCountDown), userInfo: nil, repeats: true)
                self.timeWorking = true
            }
        } else if date! < Date() {
             self.pollExpirationDate.text = "expirationDate is gone"
        }
    }
}

更新计数器方法将倒计时您的日期计时器。

@objc func updateCountDown() {
    if let expirationTimeInt = post?.pollExpirationTime {
        let expirationDate = Date(timeIntervalSince1970: Double(expirationTimeInt))

        self.pollExpirationDate.attributedText = self.timeLeftExtended(date: expirationDate)
    }
}

从viewDidLoad调用设置计时器方法。这对我来说是有效的代码,希望对您有所帮助。