1

我有 4 个 UIViewController 子类,分别命名为 AViewController、BViewController、CViewController、DViewController。

现在在工具栏中,单击 A,内容视图显示 AViewController 的视图,...等。

我是一个懒人,讨厌写 4 次 "alloc]initwithnibname" 代码,所以我写了下面的代码在代码中创建它们。

- (void)addChildView:(UIViewController *)childViewController className:(NSString *)viewClassName{
if (childViewController != nil) {
    // add view
    [self.contentView addSubview:childViewController.view];
}else
{
    // init.
    Class v = NSClassFromString(viewClassName);
    UIViewController *childViewControllerNew = nil;
    childViewControllerNew = [[v alloc] initWithNibName:viewClassName bundle:nil];
    [self.contentView addSubview:childViewController.view];
}}

但这不会创建任何 ViewController,调试时总是返回 nil。

你能告诉我有什么问题吗?我可以通过这种方法创建子类 UIViewController 吗?

提前致谢!

4

2 回答 2

1

如果你真的很懒,你可以声明枚举值,比如

typedef NS_ENUM (NSInteger, VC) {
VCa,
VCb,
VCc,
VCd
};

然后在你做的

- (void)addChildView:(UIViewController *)childViewController className:(VC)typeOfVC {
switch(typeOfVC)
      case VCa: ViewControllerA *vc = [ViewControllerA alloc] initwithNibName@"YourNibName"]
[self.contentView addSubview:vc.view];
case: VCb : same with B 
etc
etc
}

此外,您可以在其他类中使用这些案例来改变 ViewControllers ......

于 2013-06-27T12:47:55.260 回答
1

The problem is that you're creating a view controller, but then you aren't doing anything with it. There are 2 issues:

  1. A typo means you're setting the wrong view ([self.contentView addSubview:childViewController.view];)
  2. You aren't retaining childViewControllerNew

You should change the last block of code to something like:

Class v = NSClassFromString(viewClassName);
UIViewController *childViewControllerNew = nil;
childViewControllerNew = [[v alloc] initWithNibName:viewClassName bundle:nil];
[self.contentView addSubview:childViewControllerNew.view];

[self addChildViewController:childViewControllerNew];
于 2013-06-27T11:15:05.217 回答