[英]How to reload only one cell in a collectionView?
I have a collectionView and I have two problems. 我有一个collectionView,我有两个问题。 First, the scrolling is too laggy.
首先,滚动太迟了。 My collectionView receives the data from an API in url and look like this:
我的collectionView从url中的API接收数据,如下所示:
This is my code: 这是我的代码:
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
}
}
The second problem that I have is I need refresh only the third cell in my collection view. 我遇到的第二个问题是我只需要刷新集合视图中的第三个单元格。 That is my secondLabel but when I try with
myCollectionView.reloadData()
that reloads all of my cells. 这是我的第二个标签,但是当我尝试使用
myCollectionView.reloadData()
重新加载我的所有单元格时。 I need to refresh the third cell every second. 我需要每秒刷新第三个单元格。
To load a particular cell use following: 要加载特定单元格,请使用以下
let indexPath = IndexPath(item: 2, section: 0)
collectionView.reloadItems(at: [indexPath])
You are loading the image in cellForItemAt
, Just ensure you are not loading an image on the main thread 您正在
cellForItemAt
中加载图像,只是确保您没有在主线程上加载图像
You can use a library to download the image and cache an image 您可以使用库来下载图像并缓存图像
https://github.com/SDWebImage/SDWebImage https://github.com/SDWebImage/SDWebImage
https://github.com/Alamofire/AlamofireImage https://github.com/Alamofire/AlamofireImage
The problem with the lag in the collectionView can be the way tha you use NSData, consider use Alamofire Image, like this 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
}
}
})
}
Collection View laggy because you trying to show images from url on main thread. 集合查看滞后,因为您尝试在主线程上显示来自URL的图像。 Show some default images in cells before you download images from api and then update cells on main thread
在从api下载图像之前在单元格中显示一些默认图像,然后在主线程上更新单元格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.