问题
So I've got a quick question here...
I've got an instance of a view controller object, lets call it viewCon1
, and it has several subview's placed on it each with unique properties. Lets call them sub1
, sub2
, and sub3
. Now, I add each of these subviews programatically doing something to the extent of:
//create the subviews
TaskUIButton *sub1 = [[TaskUIButton alloc] init];
TaskUIButton *sub2 = [[TaskUIButton alloc] init];
TaskUIButton *sub3 = [[TaskUIButton alloc] init];
//add them to viewCon1
[viewCon1.view addSubView:sub1];
[viewCon1.view addSubView:sub2];
[viewCon1.view addSubView:sub3];
Now here is where I don't know how to proceed. I need to create another view controller object called viewCon2
and make it exactly like viewCon1
with identical (albiet separate) subviews attached to it. So for instance, lets say that viewCon1
's sub1
had a title of "foo"
, I need viewCon2
to also have an identical subview with a title of "foo"
, etc.
Is there any easy way to go about this?
I'd appreciate any insight, thanks!
回答1:
Neither UIViewController nor UIView implements the NSCopying protocol, so duplicating such objects is more than a one-step process. The general idea is to create a new instance of the class in question and copy the original object's configuration.
Since you already have code that configures the views for your view controller, the easiest thing will be to call that method again to create a second instance of the view controller. I realize that your code may not be set up to do that right now, so you may need to refactor to make that possible.
Based on your comments above, it sounds like you may be storing some state in your view rather than letting the view reflect the data stored in your application. It may help to determine what information is determining the layout of your view and make sure that data is properly represented in your app's data model. If you can do that, you should be able to simply create a new view controller based on the same data and get an identical layout.
来源:https://stackoverflow.com/questions/6495420/objective-c-copying-a-view