views:

102

answers:

3
+2  Q: 

Duplicating views

I want to create a view with some controls inside, a text field and some buttons, and I want to duplicate this to show them as content of a tab in a tabview. Each tab must has an instance of this view. Directions?

+1  A: 

Ehm...I'm not really sure whether I correctly understood what you'd like to do. The word "duplicate" doesn't sound very good since most often in programming it indicates a "smell".

I'm not a specialist of cocoa, neither of objective-c, but I guess you could somehow put your controls inside some kind of container control and instantiate (reuse rather than duplicate) this container control on your tab view or wherever you'd like.

Juri
As I said: "Each tab must has an instance of this view". Anyway, thanks for the useless answer.
goo
@goo what he said is correct. You can build the view as a View XIB then instantiate it multiple times using an NSViewController (is one way to do it).
Dave DeLong
A: 

The quick and dirty way to clone a view hierarchy is to encode it and decode it. Example:

NSData * encodedView = [NSKeyedArchiver archivedDataWithRootObject:myView];
NSView * myViewClone = [NSKeyedUnarchiver unarchiveObjectWithData:encodedView];
Dave DeLong
There are many downsides to this approach. For example, if the views have targets and actions set up, they won't be duplicated unless the target is also encoded.
Jon Hess
@Jon agreed, hence "quick and dirty" =)
Dave DeLong
+4  A: 

Dave DeLong is close and somewhat your question contains the answer ("each tab must has an instance of the view"). Create a UIViewController subclass to programatically create the view, or to load a NIB. Then instantiate several instances of your UIViewController subclass and add them all to the UITabViewController's viewControllers property.

You'll want to spend some time with the View Controller Programming Guide. The fact that you are making multiple instances of the same UIViewController subclass really has little impact on the solution.

Rob Napier
Of course, that only works on the iPhone. On the Mac, you'll use NSViewController instead, and I don't think it and UIViewController work much alike.
Peter Hosey
NSViewController is much more primitive than UIViewController, but the principles above should be identical. We've all been building "view controllers" on Mac for a long time before NSViewController came around (I'm sure you've created plenty of your own). The idea of having an object that programatically builds up a view (such as by overloading -loadView) is not specific to iPhone, and is still a reasonable approach to managing an NSSegmentedControl-based tabview or other Mac solution. That said, on Mac you might do this with an NSView subclass rather than NSViewController.
Rob Napier