使用addChildViewController时IBAction无法正常工作

时间:2015-01-19 06:53:27

标签: ios objective-c menu parent-child

我正在制作示例项目以实现顶级菜单。

以下是项目结构。

enter image description here

TopMenu是父视图,其结构如下所示。

enter image description here

在TopViewController中,下面是viewDidLoad。

NSString *whereToGo = [[NSUserDefaults standardUserDefaults] valueForKey:@"whereToGo"]; // this is DarkGray by default
UIViewController *goToViewController;
goToViewController = [self.storyboard instantiateViewControllerWithIdentifier:whereToGo];
goToViewController.view.frame = bottomView.bounds;
// bottomView is the first view (will bring child here)
[bottomView addSubview:goToViewController.view];
[self addChildViewController:goToViewController];
[goToViewController didMoveToParentViewController:self];

现在当我执行项目时,我看到深灰色,但是当我点击Click Me按钮时,什么也没发生(IBAction没有被调用)。

- (IBAction)clickme:(id)sender {
    NSLog(@"clickme==dark gray");
}

当我点击Click Me时,我所期待的是 ,我会在日志中看到clickme ==深灰色。

为什么会发生这种情况?

Sample project for download


答案

如MidhunMP所述,简短回答是

menuView隐藏了bottomView

实际上,对于menuView,我将backgroundColor作为clearColor。我假设(这是错误的),因为menuView是清晰的,触摸得不能在menuView上工作,那些触摸将转到bottomView。

2 个答案:

答案 0 :(得分:1)

问题很简单,您要将goToViewController.view添加到bottomView

menuView位于bottomView之上,因此隐藏了goToViewController.view的触摸。您需要将goToViewController.view添加到最顶层的视图,即menuView

现在您的视图层次结构如下:

bottomView -> goToViewController.view -> menuView

您需要将其更改为:

bottomView -> menuView -> goToViewController.view

将您的代码更改为以下内容并检查:

NSString *whereToGo = [[NSUserDefaults standardUserDefaults] valueForKey:@"whereToGo"]; // this is DarkGray by default
UIViewController *goToViewController;
goToViewController = [self.storyboard instantiateViewControllerWithIdentifier:whereToGo];
goToViewController.view.frame = menuView.bounds;
[menuView addSubview:goToViewController.view];
[self addChildViewController:goToViewController];
[goToViewController didMoveToParentViewController:self];

答案 1 :(得分:1)

您用作容器的视图由其他视图覆盖。