Мне нужно реализовать горизонтальный UICollectionView
.
Иногда мне нужно обновить данные, поэтому я решил реализовать refreshcontrol
.
Я позвонил reloadData()
с refreshcontrol
. Вроде бы работает, но cellForItemAt
не называется правильным временем.
Поэтому, когда количество ячеек изменилось, оно будет сбой.
class ViewController: UIViewController, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
private let refreshControl = UIRefreshControl()
private var cellCount = 1
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: .valueChanged)
collectionView.register(UINib(nibName: "TopCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal // not working
// layout.scrollDirection = .vertical //working
}
}
@objc func refresh(sender: UIRefreshControl) {
cellCount = cellCount + 1
collectionView.reloadData()
sender.endRefreshing()
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: TopCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! TopCollectionViewCell
return cell
}
}
Если направление меняется на вертикальное, оно работает.
Это правильное поведение? или просто ошибка?