Как добавить таймер для каждой ячейки таблицы, которая обновляется каждый раз, когда пользователь прокручивает? - PullRequest
0 голосов
/ 06 июня 2019

Я пытаюсь добавить счетчик времени в каждую из моих ячеек таблицы. Я включил прокрутку с нумерацией страниц, каждая ячейка моего табличного представления полноэкранная.

Что я хочу: Когда пользователь находится в ячейке, счетчик времени запускается автоматически, а при прокрутке счетчик времени останавливается, и запускается еще один счетчик для следующей ячейки ... и т. Д.

Я также хочу вести учет прошедшего времени.

что я пробовал: чтобы добавить таймер в контроллер представления вместо tableview, у меня есть 2 проблемы:

1) Таймер не сбрасывается, когда я провожу вверх, хотя я делаю его недействительным, как вы можете видеть ниже

2) Таймер запускается до того, как первая ячейка загрузит свой контент с сервера

var timer = Timer()
var counter = 0

@IBOutlet var countingLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    countingLabel.text = String(counter)
    timer = Timer.scheduledTimer(timeInterval: 0.1, target:self, selector: #selector(self.updateCounter), userInfo: nil, repeats: true)
    // Do any additional setup after loading the view, typically from a nib.

    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeLeft.direction = .left
    self.view.addGestureRecognizer(swipeLeft)

    let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeUp.direction = .up
    self.view.addGestureRecognizer(swipeUp)

    let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeDown.direction = .down
    self.view.addGestureRecognizer(swipeDown)

    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeRight.direction = .right
    self.view.addGestureRecognizer(swipeRight)
}

@objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
    if gesture.direction == UISwipeGestureRecognizer.Direction.left {
        print("Swipe Left")
        performSegue(withIdentifier: "toSettings", sender: self)
    } else if gesture.direction == UISwipeGestureRecognizer.Direction.up {
        print("Swipe Up")
        timer.invalidate()
        counter = 0
        countingLabel.text = String(counter)
        timer = Timer.scheduledTimer(timeInterval: 0.1, target:self, selector: #selector(self.updateCounter), userInfo: nil, repeats: true)
    }
    else if gesture.direction == UISwipeGestureRecognizer.Direction.right {
        print("Swipe Right")
    }
    else if gesture.direction == UISwipeGestureRecognizer.Direction.down {
        print("Swipe Down")
    }
}

@objc func updateCounter() {
    counter += 1
    countingLabel.text = String(counter)
}

Я хочу, чтобы таймер срабатывал для каждой ячейки моего табличного представления, и я хочу сохранить истекшее время в переменной, которую я могу использовать в другом месте

1 Ответ

0 голосов
/ 06 июня 2019

Вот как вы можете обрабатывать timers в каждом UITableViewCell.

Создать пользовательский UITableViewCell

class CustomCell: UITableViewCell {
    //MARK: Outlets
    @IBOutlet weak var label: UILabel!

    //MARK: Internal Properties
    var handler: ((Int)->())?

    //MARK: Private Properties
    private var timer: Timer?
    private var counter = 0 {
        didSet {
            DispatchQueue.main.async {
                self.label.text = "\(self.counter)"
                self.handler?(self.counter)
            }
        }
    }

    func configure(with counter: Int) {
        self.counter = counter
        self.setTimer()
    }

    private func setTimer() {
        self.timer?.invalidate()
        self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {[weak self] (timer) in
            self?.counter += 1
        })
    }
}

В приведенном выше коде,

  1. Я создал label, который обновит значение counter в UI.
  2. handler - он будет хранить и сохранять обновленное значение counter где-то (в ViewController, поясняется далее), когда cell перемещается за пределы экрана
  3. timer - график timer в cell с timeinterval = 1
  4. counter - текущее counter значение для каждого cell

В ViewController,

class VC: UIViewController, UITableViewDataSource {
    let numberOfCells = 20
    var timerArr = [Int]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.timerArr = [Int](repeating: 0, count: numberOfCells)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.numberOfCells
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
        cell.configure(with: self.timerArr[indexPath.row])
        cell.handler = {[weak self] (counter) in
            self?.timerArr[indexPath.row] = counter
        }
        return cell
    }
}

В приведенном выше коде,

  1. timerArr - отслеживает значение counter для каждого cell в tableView.
  2. В tableView(_:cellForRowAt:) counter для каждого cell обновляется с помощью handler, который мы создали ранее в CustomCell
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...