【发布时间】:2018-10-31 17:03:15
【问题描述】:
我有一个collectionView,我有两个问题。首先,滚动太慢了。我的 collectionView 从 url 中的 API 接收数据,如下所示:
这是我的代码:
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if imageUrl.count >= 4 {
activity.stopAnimating()
activity.isHidden = true
}else{
DispatchQueue.main.async {
self.myCollectionView.reloadData()
}
}
return imageUrl.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "myViewCell", for: indexPath) as! myViewCell
if let url = NSURL(string: imageUrl[indexPath.row]){
if let data = NSData(contentsOf: url as URL){
cell.carImageView.contentMode = UIViewContentMode.scaleAspectFit
cell.carImageView.image = UIImage(data: data as Data)
}
}
cell.firstLabel.text = firstLabelArray[indexPath.row]
if secondLabelArray != []{
cell.secondLabel.text = secondLabelArray[indexPath.row]
}
return cell
}
}
我遇到的第二个问题是我只需要刷新集合视图中的第三个单元格。那是我的第二个标签,但是当我尝试使用 myCollectionView.reloadData() 时,它会重新加载我的所有单元格。我需要每秒刷新第三个单元格。
【问题讨论】:
-
let data = NSData(contentsOf: url as URL)。不。这阻塞了当前线程,它恰好是主线程,所以被阻塞的是 UI。使用异步网络呼叫。SDWebImage,KingFisher,Alamofire+Image,AFNetworking + Image做得很好。 -
this 是您要找的吗?
-
使用 self.collectionView.reloadItems(at: [IndexPath]) 重新加载特定单元格
-
我还认为您对
collectionView(_:numberOfItemsInSection)的实施会给您带来问题。如果您在调用reloadData()的结果中调用reloadData(),我认为您将无限递归。
标签: ios swift uicollectionview