【发布时间】:2019-11-04 05:19:57
【问题描述】:
我需要实现水平UICollectionView。
有时,我需要更新数据,所以我决定实现一个refreshcontrol。
我用refreshcontrol 打电话给reloadData()。它似乎正在工作,但 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
}
}
如果方向改变为垂直,它正在工作。 这是正确的行为吗?还是只是一个错误?
【问题讨论】:
标签: ios swift uicollectionview swift4 uirefreshcontrol