Reputation: 373
Images are changing in collectionView when I scroll it swift
What can I do when scroll Images are changing?
Data from json:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell: CollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell
let mindata = (data[indexPath.row] as! NSDictionary)
cell.NameShow!.text = mindata["name"] as? String
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
{
if let url = NSURL(string: (mindata["img"] as? String)!),
data = NSData(contentsOfURL: url)
{
dispatch_async(dispatch_get_main_queue(),
{
cell.img.image = UIImage(data: data)
})
}
})
}
Upvotes: 0
Views: 1714
Reputation: 9754
You code is not full, so I can just suggest some hints:
UITableView and UICollectionView both use reuse techniques, which means the cells are reused from the pool once it's created.
Given the issue you are saying, it looks like you don't clean up your cell either bind the image to a specific location.
You can try depending on your needs:
subclass UICollectionViewCell, and in prepareReuse
, you clean up the image, so the cell is cleaned up, you can feed any image you like, if you don't care the order.
bind the image with your cell's indexPath
, which means you create your image array or tag your image with some sort of index.
For example in cellForItemAtIndexPath
,
func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
...
cell.img.image = imageArray[indexPath.row]
...
}
Upvotes: 1