I have a collectionView and I have two problems. First, the scrolling is too laggy. My collectionView receives the data from an API in url and look like this:
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. I need to refresh the third cell every second.
Since iOS 10, the UITableView and UICollectionView classes have a refreshControl property. You can add a refresh control to a table or collection view by assigning an instance of the UIRefreshControl class to this property.
reloadData()Reloads all of the data for the collection view.
The problem with the lag in the collectionView can be the way tha you use NSData, consider use Alamofire Image, like this
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
}
}
})
}
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
You can use a library to download the image and cache an image
https://github.com/SDWebImage/SDWebImage
https://github.com/Alamofire/AlamofireImage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With