2

My intension is to create a new viewcontroller with some controls(buttons, labels etc) of the current controllrer view.

//Get all the controls
NSArray* array =[[NSArray alloc]init];
   array=[self.view subviews];

for(int i =0 ;i<array.count ;i++)
{
// UIView *subview = (UIView *)[array objectAtIndex:i];
   UIView *subview =  (UIView *)[array objectAtIndex:i] ;
    ..
   [nextview.view insertSubview:subview  atIndex:i];
}

But i found out when new viewcontroller view dismiss all the controls of the parent controls also disappering. how can i copy UIView * object to another?

bitmapdata.com
  • 9,572
  • 5
  • 35
  • 43
  • Try to re-use the view if you can – Felix Aug 17 '12 at 09:18
  • You may as well check [this post](http://stackoverflow.com/questions/4425939/can-uiview-be-copied) for a solution using `NSKeyedUnarchiver`/`NSKeyedArchiver`. – lucasart Mar 09 '14 at 10:13

1 Answers1

4

You can't copy a UIView, it doesn't implement the Copying protocol. But you can easily make a method that creates a new view, then creates a new instance of all the subviews and setup them as the old view.

Something like:

@interface UIView (Copy)
- (UIView*)newDuplicate;
@end

@implementation UIView (Copy)
- (UIView*)newDuplicate {
    UIView *v = [[[self class] alloc] initWithFrame:self.frame];
    v.autoresizingMask = self.autoresizingMask;

    for (UIView *v1 in self.subviews) {
        UIView *v2 = [[[v1 class] alloc] initWithFrame:v1.frame];
        v2.autoresizingMask = v1.autoresizingMask;
        [v addSubview:v2];
    }

    return v;
}         
@end

But this will not copy all the properties of a view and it isn't a perfect solution. You should implement something like this on the view you want to copy.

fbernardo
  • 10,016
  • 3
  • 33
  • 46
  • Thanks fbernardo,as u said i need to write separate copy method for each and every possible control types such as button,label,webview etc. – Kithsiri Lekamge Aug 17 '12 at 11:16