[英]Horizontal direction UICollectionView with UIRefreshControl reloadData() not working
I need to implement horizontal UICollectionView
. 我需要实现水平UICollectionView
。 Sometimes, I need to update the data, So I decided to implement a refreshcontrol
. 有时,我需要更新数据,因此我决定实现一个refreshcontrol
。
I called reloadData()
with refreshcontrol
. 我用refreshcontrol
调用了reloadData()
。 It seems to be working, but cellForItemAt
is not called the correct time. 它似乎正在工作,但是cellForItemAt
没有被称为正确的时间。 So, when the cell count has changed it will be crashed. 因此,当单元数更改时,它将崩溃。
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
}
}
If the direction change to vertical, it is working. 如果方向更改为垂直,则说明它正在工作。 Is it correct behavior? 这是正确的行为吗? or just a bug? 还是一个错误?
在viewDidLoad()
alwaysBounceVertical
collectionView
的alwaysBounceVertical
属性设置为true
,即
collectionView.alwaysBounceVertical = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.