In my app currently we need reordering images in collectionView and the first image of collectionView should reflect on imageView, So here is my implementation
//MARK: Variable declaration
@IBOutlet var imageViewMain: UIImageView!
@IBOutlet var collectionViewImages: UICollectionView!
var listingImages : [UIImage] = [UIImage(named:"demo_advertisement")!, UIImage(named:"camera_black")!, UIImage(named:"twitter-bird-logo")!, UIImage(named:"money-bag")!]
//MARK: DataSource
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let addPhotosCell = collectionView.dequeueReusableCellWithReuseIdentifier("AddPhototsCollectionViewCell", forIndexPath: indexPath) as! AddPhototsCollectionViewCell
addPhotosCell.imageView.image = listingImages[indexPath.item]
// if listingImages.count > 0 {
// imageViewMain.image = listingImages[0]
// }
return addPhotosCell
}
func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath,toIndexPath destinationIndexPath: NSIndexPath) {
// swap values if sorce and destination
let src = listingImages[sourceIndexPath.row]
let dest = listingImages[destinationIndexPath.row]
listingImages[destinationIndexPath.row] = src
listingImages[sourceIndexPath.row] = dest
self.collectionViewImages.performBatchUpdates({
self.collectionViewImages.reloadData()
}, completion: nil)
}
What I'm trying to achieve :
Issue :
If I do
self.collectionViewImages.reloadData()
in moveItemAtIndexPath while reordering images its showing me duplicate images like
I'm calling reloadData() because I need to set first element of collectionView to imageViewMain in cellForItemAtIndexPath.
My attempt : In case if I don't call reloadData and try to set image to imageViewMain in moveItemAtIndexPath like
imageViewMain.image = listingImages[0]
after below lines, it will not reflect properly on imageViewMain.(But in this case reordering of images works perfectly without any duplicate image)
let src = listingImages[sourceIndexPath.row]
let dest = listingImages[destinationIndexPath.row]
listingImages[destinationIndexPath.row] = src
listingImages[sourceIndexPath.row] = dest
Can anyone please suggest me what is the proper way to implement this ?
Actually the logic which i was written in
moveItemAtIndexPath
was wrong. Instead of
let src = listingImages[sourceIndexPath.row]
let dest = listingImages[destinationIndexPath.row]
listingImages[destinationIndexPath.row] = src
listingImages[sourceIndexPath.row] = dest
It should be
let src = listingImages[sourceIndexPath.row]
listingImages.removeAtIndex(sourceIndexPath.row)
listingImages.insert(src, atIndex: destinationIndexPath.row)
collectionViewImages.reloadData()