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

Я пытаюсь создать приложение с таймером обратного отсчета с collectionView.

Особенности и функции:

  • Каждая ячейка имеет собственную метку и функцию таймера.
  • Таймер CountDown запускается, если пользователь касается ячейки.
  • Строка времени должна обновляться при запуске таймера.

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

Пожалуйста, проверьте коды ниже и дайте мне подсказку.

class ListViewController: UIViewController {

@IBOutlet weak var collectionView: UICollectionView!


var recipeList: TimeRecipeList
var timer = Timer()

required init?(coder aDecoder: NSCoder) {
    recipeList = TimeRecipeList()
    super.init(coder: aDecoder)
}



override func viewDidLoad() {
    super.viewDidLoad()
    let width = (view.frame.size.width - 10) / 2
    let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = CGSize(width: width, height: width)

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "AddItemSegue" {
        if let addItemVC = segue.destination as? AddRecipeViewController {
            addItemVC.delegate = self
        }
    }
}

}

extension ListViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return recipeList.item.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeListCell", for: indexPath)
        let item = recipeList.item[indexPath.row]
        configureText(for: cell, with: item)
        return cell
    }

    func configureText(for cell: UICollectionViewCell, with item: TimeRecipe) {
        if let label = cell.viewWithTag(1) as? UILabel {
            label.text = item.name
        }

        if let label = cell.viewWithTag(2) as? UILabel {
            let formatter = DateComponentsFormatter()
            formatter.unitsStyle = .abbreviated
            let timeString = formatter.string(from: TimeInterval(item.time))
            label.text = timeString
        }
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeListCell", for: indexPath)
        let item = recipeList.item[indexPath.row]

        let cellTimer = TimerControl()
        cellTimer.second = item.time
        cellTimer.timerRun()

        configureText(for: cell, with: item)

    }


    class TimerControl {

        var timer = Timer()
        var second: Int = 0


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

        @objc func countDown() {
            //let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeListCell", for: indexPath)

                if second <= 1 {
                    timer.invalidate()
                } else {
                    second -= 1
                    //collectionView.reloadItems(at: [indexPath])

                    //MARK: Reload selected cell
               }
        }

    }


}

extension ListViewController: AddRecipeViewControllerDelegate {
    func addRecipeViewControllerDidCancel(_ controller: AddRecipeViewController) {
        dismiss(animated: true)
    }

    func addRecipeViewControllerDisSave(_ controller: AddRecipeViewController, didFinishAdding item: TimeRecipe) {
        dismiss(animated: true)
        let rowIndex = recipeList.item.count
        recipeList.item.append(item)

        let indexPath = IndexPath(row: rowIndex, section: 0)
        let indexPaths = [indexPath]
        collectionView.insertItems(at: indexPaths)
    }


}

1 Ответ

0 голосов
/ 15 марта 2019
@objc func countDown(indexPath: IndexPath) {
        if second <= 1 {
            timer.invalidate()
        } else {
            second -= 1
            //MARK: Reload selected cell
            yourarray[indexPath.row] = newvalues
            collectionView.reloadItems(at: [indexPath])
        }
    }
...