首页 > 解决方案 > 尝试为 cellForRowAtIndexPath 重用计时器

问题描述

所以我的目标是为每个单元重复使用一个计时器。除了一个优点外,每一件事都运行良好。cell.indexpath.row 从 1 而不是 0 开始。即使我滚动到顶部,并且它反弹回来,它也会变为 1。问题是计时器是基于 IndexPath 创建的。我已经尝试了很多增加单元大小的解决方法,不成功地尝试开始和结束更新路线,但似乎无法锁定它。任何基于我已经拥有的代码的建议,或新的解决方案问题?

定时器VC

     var timer = Timer()
    func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return LiveActivityArray.count

}

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

        if let cell = tableView.dequeueReusableCell(withIdentifier: "liveCell", for: indexPath) as? liveActivitiesCell {
            //print("VISBLE CELL \(tableView.indexPathsForVisibleRows)")
            // var visibleCells = self.tableview.visibleCells
var prop = hudProp()
                    Prop = LiveActivityArray[indexPath.item]
            cell.configureCell(properties: Prop, timer: &timer)
                    cell.property = Prop
                    cell.delegateFavorite = self
                    cell.delegate = self
                    cell.indexpath = indexPath
                    print("INDEX PATH CELL \(cell.indexpath.row)")

                    cell.StartTimerFilter(timer: &timer)

                    return cell
    }
    }
      return UITableViewCell()

}

表格视图单元格

func configureCell(properties: hudProp, timer: inout Timer) {

  if DataService.instance.BothDatesReturnedTrue == true {
        timer.invalidate()
    StartTimerFilter(timer: &timer)
    }


@objc func TimerFuncFilter(timer: Timer) {

     property.getAuctionTime(property.Begin, AuctionEnd: property.End, postAuctionStart: _leftLabel: leftTime, _leftLabelDayHour: leftTimeDaysHrs, _midLabel: midTime, _midLabelHourMin: midTimeHrsMin, _rightLabel: rightTime, _rightLabelMinSec: rightTimeMinSec, _timer: timer, EndsLabelFunc: EndsOnLabel, EndsDateLabelFunc: EndsOnDateLabel)
    }
}
func StartTimerFilter(timer: inout Timer) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(liveActivitiesCell.TimerFuncFilter), userInfo: nil, repeats: true)
     DataService.instance.BothDatesReturnedTrue = false
}

如您所见,我不断使每个新单元格的计时器无效,但问题仍然是它从一个开始。我可以继续使用这段代码并修改一些东西,还是应该重新考虑这个问题的架构。

提前谢谢你,我已经尝试解决这个问题几周了,有很多失败的解决方案。

标签: iosswiftuitableviewtimernstimer

解决方案


因此,如果有人在苦苦挣扎或遇到类似情况,解决方案是在您的视图控制器中没有计时器,而是将其完全保留在您的视图中。使许多计时器不会进入保留周期的第二个方面是使用

func prepareForReuse() {
super.prepareForReuse
 timer.invalidate
}

推荐阅读