Сбой при просмотре ячеек представления коллекции scrollToItem [Swift] - PullRequest
1 голос
/ 04 мая 2020

В моем быстром приложении есть представление коллекции с большим количеством элементов, я хочу прокрутить до элемента, а затем установить правильность пользовательского класса ячейки коллекции, но приведение не удается, почему? Вот мой код, я пропустил некоторые очевидные шаги, но в результате получается печать «Ошибка приведения»:

class ViewController: UIViewController {

lazy var collectionView: UICollectionView = {
    let cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: UICollectionViewFlowLayout())
    cv.backgroundColor = .gray
    cv.register(Cell.self, forCellWithReuseIdentifier: Cell.id)
    cv.delegate = self
    cv.dataSource = self
    return cv
}()

}

расширение ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.id, for: indexPath) as! Cell
    cell.backgroundColor = .purple
    cell.label.text = "\(indexPath)"
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if indexPath.item == 14 {
        collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .top, animated: true)
        guard let cell = collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? Cell else {
            print("Cast fails")
            return
        }
        cell.label.text = "Something"
    }
}

}

Вот решение, которое я нашел:

extension UICollectionView {
    func scrollToItem(at indexPath: IndexPath, at position: UICollectionView.ScrollPosition, completion: @escaping () -> ()) {
        scrollToItem(at: indexPath, at: .top, animated: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            completion()
        }
    }
}

1 Ответ

0 голосов
/ 04 мая 2020

Приведение не выполняется, так как ячейка (с указанным c индексом) не видна в тот момент, когда вы запрашиваете ее

guard let cell = collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? Cell else {
  print("Cast fails")
  return
} 

, вместо этого вы можете попытаться установить , at: .top, animated: false) или обернуть вышеупомянутое. фрагмент кода внутри Dispatch after block

Кстати, вам лучше изменить массив dataSource и перезагрузить этот индекс, чтобы вам не нужно было ждать

// change source array at that index
// scroll to that row with/without animation
// make sure you set value for the cell label in cellForRowAt table's datasource method 
...