Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate, clone or copy UIView

Tags:

I have a UIView that is linked to a UIViewController via the Interface Builder. Is it possible to duplicate, clone or copy this view so that I can use it more than once?

like image 651
Thizzer Avatar asked Feb 15 '11 13:02

Thizzer


1 Answers

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.

like image 178
osxdirk Avatar answered Oct 19 '22 21:10

osxdirk