Duplicate, clone or copy UIView Duplicate, clone or copy UIView ios ios

Duplicate, clone or copy UIView

The following category might not be particularly efficient, but worked for me in one project:

@implementation UIView (OPCloning)- (id) clone {    NSData *archivedViewData = [NSKeyedArchiver archivedDataWithRootObject: self];    id clone = [NSKeyedUnarchiver unarchiveObjectWithData:archivedViewData];    return clone;}@end

I'd not implement -copy or -copyWithZone: as Apple might do so in the future.Note, that not all views implement archiving to the same extent. You'll definitely need to implement the NSCoding methods for custom properties of your NSView subclasses to be cloned (will turn to nil in the cloned view, otherwise). Still easier than writing custom cloning code.

Here is a new method you can use: Use UIView's method:

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates

This is the fastest way to draw a view. Available in iOS 7.

You can try with Swift 3.0.1 below:

extension UIView{func copyView() -> AnyObject{    return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))! as AnyObject }}