跟踪每个 Cell 上的时间,例如 Hours App

Tracking the time on each Cell like Hours App

我有一个 UITableViewCell,其中一些按钮具有时间值,例如小时应用程序。每当我像小时应用程序一样单击与该单元格相关的按钮时,我想跟踪每个单元格上的时间 - 如下面的屏幕截图所示。

我已经知道如何处理计时器:下面的函数用于更新一般标签上的时间:

var startTime = TimeInterval()
var timer : Timer?


func updateTime() {

        let currentTime = NSDate.timeIntervalSinceReferenceDate

        //Find the difference between current time and start time.

        var elapsedTime: TimeInterval = currentTime - startTime

        //calculate the minutes in elapsed time.
        let minutes = UInt8(elapsedTime / 60.0)

        elapsedTime -= (TimeInterval(minutes) * 60)

        //calculate the seconds in elapsed time.
        let seconds = UInt8(elapsedTime)

        elapsedTime -= TimeInterval(seconds)

        //add the leading zero for minutes, seconds and millseconds and store them as string constants

        let strMinutes = String(format: "%02d", minutes)
        let strSeconds = String(format: "%02d", seconds)

        //concatenate minuets, seconds and milliseconds as assign it to the UILabel

        self.timeLabel?.text = "\(strMinutes):\(strSeconds)"
        //labelShake(labelToAnimate: self.timeLabel!, bounceVelocity: 5.0, springBouncinessEffect: 8.0)

    }

我可以把下面的代码放在ViewDidLoad中来启动定时器:

        timer = Timer()
        timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
        startTime = NSDate.timeIntervalSinceReferenceDate

为了点击单元格中的按钮,我在单元格的按钮上添加了一个标签来跟踪我点击的单元格,如下所示

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        //...
        cell.timerViewButton.tag = indexPath.row
        cell.timerViewButton.addTarget(self, action: #selector(startTimerForCell), for: UIControlEvents.touchUpInside)
        //...

       return cell

}

// 我可以跟踪点击这里的按钮。

func startTimerForCell(sender : UIButton) {


        print("SelectedCell \(sender.tag)")


    }

任何人都可以帮助我如何更改单击的单元格上的按钮标题以进行计数并可能在我单击按钮时停止计时器

据我了解,您的问题是想要跟踪每个计时器状态。请记住,UITableViewCell 是可重复使用的,并且当您滚动或查看它时它会保持变化。

通常我会使用数组来轻松跟踪单元格中的所有这些状态或值。

因此,在您的控制器中将有 class 个变量,可能如下所示

struct Timer {
    let start = false
    let seconds = 0
    // can have more properties as your need
}

var timers = [Timer]()

然后,在您的启动函数中 startTimerForCell 将继续监视那些数组。

func startTimerForCell(sender : UIButton) {
    let timer = timers[sender.tag]
    if timer.start {
        // stop the timer
        timers[sender.tag].start = false
    }
    else {
        // stop the timer
        timers[sender.tag].start = true
    }
}