Can UIView be copied? Can UIView be copied? ios ios

Can UIView be copied?


this might work for you ... archive the view and then unarchive it right after. This should give you a deep copy of a view:

id copyOfView = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];


Your app probably crashes with something like:

 [UIView copyWithZone:]: unrecognized selector sent to instance 0x1c6280

The reason is that UIView does not implement the copying protocol, and therefore there is no copyWithZone selector in UIView.


You can make an UIView extension. In example swift snippet below, function copyView returns an AnyObject so you could copy any subclass of an UIView, ie UIImageView. If you want to copy only UIViews you can change the return type to UIView.

//MARK: - UIView Extensions    extension UIView    {       func copyView<T: UIView>() -> T {            return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T       }    }

Example usage:

let sourceView = UIView()let copiedView = sourceView.copyView()