Because objects are reference types, not value types, if you set a UIView
equal to another UIView
, the views are the same object. If you modify one you'll modifying the other as well.
I have an interesting situation where I would like to add a UIView
as a subview in another view, then I make some modifications, and those modifications should not affect the original UIView
. How can I make a copy of the UIView
so I can ensure I add that copy as a subview instead of a reference to the original UIView
?
Note that I can't recreate the view in the same way the original was created, I need some way to create a copy given any UIView
object.
Update for iOS 12.0
Methods
archivedData(withRootObject:)
andunarchivedObject(with:)
are deprecated as of iOS 12.0.Here is an update to @Ivan Porcolab's answer using the newer API (since 11.0), also made more general to support other types.
This answer shows how to do what @uliwitness suggested. That is, get an identical object by archiving it and then unarchiving it. (It is also basically what Ivan Porkolab did in his answer, but in a more readable format, I think.)
Notes
AnyObject
. We usedas! UIView
to type cast it back to aUIView
since we know that's what it is. If our view were aUITextView
then we could type cast itas! UITextView
.myViewCopy
no longer has a parent view.UIImage
. However, see this and this answer.Updated to Swift 3.0
I think that you should link you UIView with a .nib and just create a new one.
Property will not be the same, but you keep appearance and methods.
You can make an UIView extension. In example snippet below, function copyView returns an AnyObject so you could copy any subclass of an UIView, ie UIImageView. If you want to copy only UIView you can change the return type to UIView.
Example usage:
An addition solution could be to just create a new
UIView
and then copy over any critical properties. This may not work in the OP's case, but it could very well work for other cases.For example, with a
UITextView
, probably all you would need is the frame and attributed text:Additionally you can use this pattern to copy View controller view
You may need this for caching view controller or cloning.