Eri*_*ick 6 ios uicollectionview swift
我有一个 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
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的第二个问题是我只需要刷新集合视图中的第三个单元格。那是我的第二个标签,但是当我尝试myCollectionView.reloadData()
重新加载我的所有单元格时。我需要每秒刷新第三个单元格。
Sat*_*ish 10
要加载特定的单元格,请使用以下命令:
let indexPath = IndexPath(item: 2, section: 0)
collectionView.reloadItems(at: [indexPath])
Run Code Online (Sandbox Code Playgroud)
您正在加载图像cellForItemAt
,只需确保您没有在主线程上加载图像
您可以使用库下载图像并缓存图像
https://github.com/SDWebImage/SDWebImage
https://github.com/Alamofire/AlamofireImage
collectionView 中的滞后问题可能是您使用 NSData 的方式,考虑使用 Alamofire Image,如下所示
if imageUrl.count > 0 {
let eachImage = imageUrl[indexPath.row]
Alamofire.request(eachImage).responseImage(completionHandler: {(response) in
print("answer\(response)")
if let image = response.result.value{
DispatchQueue.main.async {
cell.ImageView.image = image
}
}
})
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8735 次 |
最近记录: |