在iOS中循环创建不同类的实例的最佳方法

时间:2013-01-16 08:04:40

标签: ios uiviewcontroller instance

我有3个不同的UIViewController,我想以最有效的方式创建每个实例。现在我一个接一个地创建并且它可以工作,但我想可能可以在循环中创建所有这些,因为唯一的区别是类名和框架但我不知道该怎么做。这是代码

Sub1ViewController *sub1 = [self.storyboard instantiateViewControllerWithIdentifier:@"Sub1"];
sub1.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.scrollViewMain addSubview:sub1.view];

Sub2ViewController *sub2 = [self.storyboard instantiateViewControllerWithIdentifier:@"Sub2"];
sub2.view.frame = CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.scrollViewMain addSubview:sub2.view];

Sub3ViewController *sub3 = [self.storyboard instantiateViewControllerWithIdentifier:@"Sub3"];
sub3.view.frame = CGRectMake(2*self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.scrollViewMain addSubview:sub3.view];

你们怎么认为这可能是一个更好的实施?

由于

1 个答案:

答案 0 :(得分:0)

- (void)myMethod
{
    [self addControllerWithID:@"Sub1" frame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self addControllerWithID:@"Sub2" frame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self addControllerWithID:@"Sub3" frame:CGRectMake(2*self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height)];
}

- (void)addControllerWithID:(NSString *)controllerID frame:(CGRect)frame
{
    UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:controllerID];
    controller.view.frame = frame;
    [self.scrollViewMain addSubview:controller.view];
}