2

我有 3 个按钮,我试图将它们作为自定义标题添加到我的应用程序中的某些视图中。将它们添加到情节提要中效果很好,我可以将它们连接到视图控制器中的方法。

我最近想将这些按钮添加到其他一些页面,并希望将它们抽象为一个可以在不同页面上重复使用的控件。我已经设置好了,但是使用普通方法添加它时遇到了困难。

也许这张照片将有助于解释我在说什么

通常我将视图控制器添加为子视图控制器,然后将视图添加为子视图,在这种情况下,我将其添加到情节提要中的占位符中,代码如下所示:

// Setup Header
HeaderViewController * headerViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"HeaderViewController"];
[headerViewController.view setFrame:CGRectMake(0.0f, 0.0f, [headerViewController.view frame].size.width, [headerViewController.view frame].size.width)];
[_headerView addSubview:headerViewController.view];

这使我可以使视图看起来正确,但是当我单击按钮时它会崩溃,因为它找不到具有与按钮单击关联的 IBActions 的视图控制器。通常我会添加以下代码,它会得到照顾:

[self addChildViewController:headerViewController];

但是,在这种情况下,我收到一条错误消息:

由于未捕获的异常“UIViewControllerHierarchyInconsistency”而终止应用程序,原因:“子视图控制器:应该有父视图控制器:但实际父视图是:”

我理解这意味着它认为自定义标题视图控制器的父级应该是导航控制器,将其设置为导航控制器的子级也不起作用。它将标题视图添加到正在显示的 PageViewControllers 视图之上。我可能错过了一些简单的东西

我尝试过的一些组合在模拟器上工作,但它们都不能在设备上工作,所以如果你使用类似的配置,请确保在设备上查看它,如果它似乎在模拟器中工作。

有什么想法或其他信息可以提供帮助吗?

4

2 回答 2

2

Put your IBActions on the header view controller instead and bind them in the xib without referencing any other view controller.

Then, in the header view controller you can pass them down to it's parent. That way it's determining who recieves the action at runtime, not as part of your xib.

- (IBAction)button1Pressed {
    if ([self.parentViewController respondsToSelector:@selector(button1Pressed)])
        [self.parentViewController performSelector(button1Pressed)];
    else
        NSLog(@"Parent doesn't care about button 1 : %@", self.parentViewController);
}

You can also check to see if the parent can respond or not :)

于 2012-11-28T15:41:20.173 回答
0

我无法使用建议的其他方法来完成这项工作,并不是说他们错了,我只是无法让他们工作。

我最终创建了一个带有相应 xib 的 UIView 子类,并将 IBActions 放入 UIView 子类中。这需要到持有视图控制器的弱链接,以便为触发的 IBAction 适当地显示模态视图。

于 2012-11-29T16:45:44.983 回答