iOS 按下手动加载的按钮时崩溃 viewcontroller

iOS crash when pressing button from manually loaded viewcontroller

我以编程方式从 xib 实例化一个 UIViewController,将其作为子 VC 添加到现有主视图,然后将子 VC 的视图(包含一个按钮)添加到我的主视图。带有按钮的视图显示得很好,但是当我按下按钮时,应用程序崩溃并显示 "unrecognized selector" 消息。

我通过创建 UIViewController 的自定义子class 创建了 XIB(文件 - 新建 - Cocoa 触摸 class,选择 UIViewController 的子class,并要求 Xcode 也生成 XIB 文件)。然后我在那个 XIB 上放置了一个按钮,并将它连接到新创建的 UIViewController subclass。 XIB 文件的所有者设置为新 class.

的名称

所以在我看来,ButtonPushed 操作消息没有发送到我的自定义 UIVC,而是发送到通用 UIViewController - 它正确地不理解 ButtonPushed 消息。

我如何确保按下按钮时发送的操作消息确实发送到我的自定义 UIViewController?

这是我用于主视图的 awakeFromNib 方法中的代码(主视图来自 Main.storyboard):

UIViewController *vc2 = [[UIViewController alloc] initWithNibName:@"ButtonVC" bundle:nil];

vc2.view.frame = CGRectMake(90, 140, 50, 200); //dont obscure the main view completely.

[self addChildViewController:vc2];
[self.view addSubview:vc2.view];  //vc2.view has a button, which shows up fine

[vc2 didMoveToParentViewController:self];

我已经设法通过仅使用按钮创建故事板并以编程方式加载它,然后实例化我的 buttonViewController,将其及其视图作为子 VC 添加到我的主视图来获得等效的功能.这很好用,但在我看来我应该可以用 "only" XIB 来实现。

试试这个:

UIViewController *vc2 = [[ButtonVC alloc] initWithNibName:@"ButtonVC" bundle:nil];

还要确保 xib 中视图控制器的 class 设置正确 ()