容器视图控制器addSubview异常

时间:2012-07-03 02:02:14

标签: ios uiviewcontroller containers addsubview

我正在构建一个Custom Container ViewController来容纳一个nib的几个实例。这个笔尖包含一个ViewController子类为DemoViewController

在Container的viewWillAppear期间,我执行以下操作:

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"Container will appear");


    if (_selectedViewController.parentViewController == self)
    {
        // nowthing to do
        return;
    }

    DemoViewController *vc = [[DemoViewController alloc] initWithNibName:@"Gauge" bundle:nil];

    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"Gauge" owner:self options:nil];
    // assuming the view is the only top-level object in the nib file (besides File's Owner and First Responder)
    UIView *nibView = [nibObjects objectAtIndex:0];

    // add as child VC
    [self addChildViewController:vc];

    [view1 addSubview:nibView];

    // notify it that move is done
    [vc didMoveToParentViewController:self];

}

在运行时,我收到以下异常:

2012-07-02 21:59:22.734 ContainerViewController[21747:f803] Loading Container View
2012-07-02 21:59:22.737 ContainerViewController[21747:f803] Container will appear
2012-07-02 21:59:22.740 ContainerViewController[21747:f803] Gauge View Loaded
2012-07-02 21:59:22.742 ContainerViewController[21747:f803] Gauge will move to parent controller
2012-07-02 21:59:22.743 ContainerViewController[21747:f803] -[DemoViewController superview]: unrecognized selector sent to instance 0x6a7daa0
2012-07-02 21:59:22.745 ContainerViewController[21747:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[DemoViewController superview]: unrecognized selector sent to instance 0x6a7daa0'
*** First throw call stack:
(0x13c9022 0x155acd6 0x13cacbd 0x132fed0 0x132fcb2 0x4fe4f 0x4a14b 0x2d2c 0xdc38f 0xdc5eb 0xdd4ed 0x4aa0c 0x4ff92 0x4a14b 0x39550 0x39670 0x39836 0x4072a 0x11596 0x12274 0x21183 0x21c38 0x15634 0x12b3ef5 0x139d195 0x1301ff2 0x13008da 0x12ffd84 0x12ffc9b 0x11c65 0x13626 0x276d 0x26d5)
terminate called throwing an exception(lldb) 

任何人都知道这里发生了什么?不幸的是,关于容器视图控制器的文档很少,所以我很难过。

3 个答案:

答案 0 :(得分:3)

顺便问一下,为什么要尝试通过NIB检索视图呢?为什么不以下?

childController = [[FirstContainedViewController alloc] initWithNibName:@"FirstContainedView" bundle:nil];
[self addChildViewController:childController];
[self.view addSubview:childController.view];
[childController didMoveToParentViewController:self];

这对我有用,看起来更简单。我不明白为什么你在做你正在做的事情。

答案 1 :(得分:1)

事实证明,通过“Xcode's File-> New-> New File-> Cocoa Touch-> UIViewController子类 - >创建一个笔尖,用XIB为用户界面”解决了我的问题。

我最初是单独创建所有内容并通过单击nib的框架将它们链接在一起并将其链接到视图控制器(就像在storyboard中一样)。结果证明是完全错误的。

相反,您需要将文件所有者链接到ViewController文件。

感谢大家的帮助!

答案 2 :(得分:0)

您的NSLog()完美地说明了问题。该XIB的顶级对象显然不是UIView,它很可能是文件的所有者对象,它指向DemoViewController。在调用方法时,您已将-addSubview发送到视图控制器。