0

我有 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];

你们如何认为这可能是一个更好的实现?

谢谢

4

1 回答 1

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];
}
于 2013-01-16T08:27:47.470 回答