1

I want to copy a custom collectionview cell from a viewcontroller to another, the problem is the collectionview cell disappears once I tap on it because of - apparently - adding it in the 2nd viewcontroller's as a subview.

I tried most of the methods here Create a copy of a UIView in Swift

One about Archiving returns nil.

Other about prototypes and structs, it doesn't return a new address for the view.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        struct ObjectToCopied {
            var objToBeRetrieved: UIView? = nil

            init(objToSaved : UIView?) {
                objToBeRetrieved = objToSaved
            }
        }
        let pickedView : UIView? = collectionView.cellForItem(at: indexPath)
        let tempObj = ObjectToCopied(objToSaved: pickedView)
        let copiedObj = tempObj
        let copiedView = copiedObj.objToBeRetrieved as? UIView
// here the copiedview's address is THE SAME as tempObj's ObjToBeRetrieved.
    }

Custom CollectionView cell image example:

Custom CollectionView cell image example

Community
  • 1
  • 1
Newsonic
  • 413
  • 4
  • 19

2 Answers2

3

Don't copy UIView object!

Your model isn't good. You have to store the data – information somewhere outside the cell directly.

You have to call your 'database' using indexPath to retrieve the information. No more!

About your question. This object doesn't copy your object.

struct ObjectToCopied {
            var objToBeRetrieved: UIView? = nil

            init(objToSaved : UIView?) {
                objToBeRetrieved = objToSaved
            }
        }

ObjectToCopied is a value type. But UIView is a reference type. So, objToBeRetrieved contains the same address as pickedView. Solution? Use objToBeRetrieved = objToSaved.copy(). But, please, really don't do it. That's really bad. Futhermore, I think this will corrupt something. Use better application model – the first suggestion.

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
2

Why do you need to copy the collectionView cell? You can simply pass your data to next viewController and create new view or cell (whatever you need) and display data on it.

Any specific reason to copy collectionView cell?

nitin.agam
  • 1,949
  • 1
  • 17
  • 24