Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UITableViewCell中的多个计时器(Swift)_Ios_Swift_Uitableview_Nstimer - Fatal编程技术网

Ios UITableViewCell中的多个计时器(Swift)

Ios UITableViewCell中的多个计时器(Swift),ios,swift,uitableview,nstimer,Ios,Swift,Uitableview,Nstimer,我有UITableViewcells,它们是在不同的时间创建的,我希望它们中的每一个都有一个独立的计时器,当对象添加reloadData() 这就是我到目前为止所做的 import UIKit var timer = Timer() var blinkStatus:Bool! = false var time = 300 class LiveViewCell: UITableViewCell { let str = String(format:"%02d:%02d", (time

我有
UITableViewcells
,它们是在不同的时间创建的,我希望它们中的每一个都有一个独立的计时器,当对象添加
reloadData()

这就是我到目前为止所做的

import UIKit

var timer = Timer()
var blinkStatus:Bool! = false
var time = 300


class LiveViewCell: UITableViewCell {

    let str = String(format:"%02d:%02d", (time / 60), (time % 100))
    func processTimer() {

        if time > 0 {
            time -= 1
            timeRemainingLbl.text = String(time)
        } else if time == 0 {
            timer.invalidate()
            timeRemainingLbl.text = "Due!"
            timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(LiveViewCell.blinkTimer), userInfo: nil, repeats: true)

        }

    }

    func blinkTimer() {
        if blinkStatus == false {
            timeRemainingLbl.textColor = UIColor(red:1.00, green:0.00, blue:0.00, alpha:1.0)
            blinkStatus = true
        } else if blinkStatus == true {
            timeRemainingLbl.textColor = UIColor.clear
            blinkStatus = false
        }

    }


    @IBOutlet weak var tableNumberLeftLabel: UILabel!
    @IBOutlet weak var guestNumbersLabel: UILabel!

    @IBOutlet weak var timeInTableLabel: UILabel!
    @IBOutlet weak var tableNumberLbl: UILabel!
    @IBOutlet weak var timeRemainingLbl: UILabel!


    var table: Table!


    func configureLiveCell(_ NT: Table) {

        layer.cornerRadius = 20
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(LiveViewCell.processTimer), userInfo: nil, repeats: true)
        tableNumberLbl.text = "T" + String(NT.number)
        timeRemainingLbl.text = String(time)

    }
}

每当我创建一个新单元格时,调用
configureLiveCell
就会出现问题。计时器似乎在加速,我希望每个计时器都是独立的。

覆盖
prepareforeuse
方法

override func prepareForReuse() {
    super.prepareForReuse()

    timer.invalidate()
}
这将在返回单元格供另一行使用之前调用。通过在此处使计时器无效,您的
configureLiveCell
不会创建另一个计时器

顺便说一句-您还应该添加一个
deinit
方法,并在那里使计时器失效

您还可以将
计时器
属性设置为可选,并在使其无效后将其设置为
nil
。当然,您需要添加适当的检查来处理它,因为它是可选的


您必须做的最后一个更改是更改
计时器
时间
、和
闪烁状态
,以便通过在类中移动它们来将它们作为实例变量。

下面是一个代码,用于管理swift 2.0中UITableview单元格中的计时器

在ViewController中

class ViewController: UIViewController, UITableViewDelegate , UITableViewDataSource{

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TblCell", forIndexPath: indexPath) as! TblCell

        cell.selectionStyle = .None
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell : TblCell = (tableView.cellForRowAtIndexPath(indexPath) as? TblCell)!
        cell.setupTimer(with: indexPath.row)
    }
}
在UITableviewCell中

class TblCell: UITableViewCell {
    @IBOutlet weak var lblTimer: UILabel!

    var couponTimer : NSTimer?
    var startTime : NSDate!
    var currentIndex : Int = 1

    func setupTimer(`with` indexPath: Int){
        currentIndex = indexPath + 1

        self.startTime = NSDate()

        if self.couponTimer != nil {
            self.couponTimer?.invalidate()
            self.couponTimer = nil
        }

        couponTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.calculateTime), userInfo: nil, repeats: true);

        NSRunLoop.currentRunLoop().addTimer(couponTimer!, forMode: NSRunLoopCommonModes)
        couponTimer?.fire()
    }

    func stopTimer(){
        if self.couponTimer != nil {
            self.couponTimer?.invalidate()
            self.couponTimer = nil
        }
    }

    func calculateTime() {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        let dateFormatter1 = NSDateFormatter()
        dateFormatter1.dateFormat = "yyyy-MM-dd"

        let tomorrow = NSCalendar.currentCalendar()
            .dateByAddingUnit(
                .Day,
                value: currentIndex,
                toDate: NSDate(),
                options: []
        )

        let tomorrowDate = dateFormatter1.stringFromDate(tomorrow!)
        let tomorrowActiveDate = dateFormatter.dateFromString(tomorrowDate + " " + "10:15:00")

        let currentDate   = NSDate()

        let strTimer : String = tomorrowActiveDate!.offsetFrom(currentDate)
        self.lblTimer.text = strTimer
        self.lblTimer.textColor = UIColor.whiteColor()
        self.lblTimer.backgroundColor = UIColor(red: 255.0/255.0, green: 44.0/255.0, blue: 86.0/255.0, alpha: 1.0)
    }
}
扩展

extension NSDate {

    func offsetFrom(date:NSDate) -> String {

        let dayHourMinuteSecond: NSCalendarUnit = [.Day, .Hour, .Minute, .Second]
        let difference = NSCalendar.currentCalendar().components(dayHourMinuteSecond, fromDate: date, toDate: self, options: [])

        var seconds : String = ""
        var minutes : String = ""
        var hours : String = ""
        var days : String = ""

        let tmp1 : String = String(format: "%.2d", difference.second)
        let tmp2 : String = String(format: "%.2d", difference.minute)
        let tmp3 : String = String(format: "%.2d", difference.hour)
        let tmp4 : String = String(format: "%d", difference.day)

        seconds = "\(tmp1)"
        minutes = "\(tmp2)" + ":" + seconds
        hours = "\(tmp3)" + ":" + minutes
        days = "\(tmp4)d" + " " + hours

        if difference.second >= 0 && difference.minute >= 0 && difference.hour >= 0 && difference.day >= 0 {
            return days
        }
        else {
            return ""
        }
    }
}

我应该将prepareForReuse()放在您的单元格类中的什么位置。它可以工作,但每当我转到另一个视图控制器时,所有单元格都会加起来并加速。我没有提到这个LiveViewCell会出现在所有的ViewControllers中。我在回答中说的你都做了吗?您是否将变量转换为适当的实例变量而不是全局变量?您是否添加了
deinit
方法?您是否添加了
prepareforeuse
?除了
deinit
方法之外,我什么都做了。我在这里写了
timer?.invalidate()
。现在的问题是,并非所有计时器都在每个
viewController
中共享相同的新时间,并从300开始重新计时。看起来他们是独立的,但不共享同一个新时间。